html to canvas php
Html to canvas php
JavaScript HTML renderer
The script allows you to take «screenshots» of webpages or parts of it, directly on the users browser. The screenshot is based on the DOM and as such may not be 100% accurate to the real representation as it does not make an actual screenshot, but builds the screenshot based on the information available on the page.
The script renders the current page as a canvas image, by reading the DOM and the different styles applied to the elements.
It does not require any rendering from the server, as the whole image is created on the client’s browser. However, as it is heavily dependent on the browser, this library is not suitable to be used in nodejs. It doesn’t magically circumvent any browser content policy restrictions either, so rendering cross-origin content will require a proxy to get the content to the same origin.
The script is still in a very experimental state, so I don’t recommend using it in a production environment nor start building applications with it yet, as there will be still major changes made.
The library should work fine on the following browsers (with Promise polyfill):
As each CSS property needs to be manually built to be supported, there are a number of properties that are not yet supported.
To render an element with html2canvas, simply call: html2canvas(element[, options]);
The function returns a Promise containing the element. Simply add a promise fulfillment handler to the promise using then :
Convert HTML into the Canvas and save into the DB with PHP
Most of the web developer faces this problem. How to convert HTML into an image and save into the Database with PHP. I also face this problem and I found so many JS Plugins that you can use to convert any type of HTML into an image in HTML5 canvas tag.
What is Canvas tag?
According to the Mozilla Org. canvas is the element which can b used for a graphic with the help of scripting like JavaScript. See the below example of the canvas.
The best plugin to convert HTML into an image is html2canvas. But I found a blurry image bug in this plugin. This bug is resolved by graham73may click here to see detail. Download plugin js file after fixing the blurry image issue from here.
To save the file into the database you need to create a table. Copy paste below code to create a table.
In this example, we use ajax to send image data to save into sever and database. Consider below code that we use to convert HTML into a canvas. Then send canvas data to a convert.php file to save into DB.
Here you can see we use a div with the id of preview that we use to convert HTML into a canvas. You can make it display none. In this example, we show you what HTML you convert into a canvas.
How to save into DB with PHP?
As you know PHP is a server side language. First, we need to develop a connection with the MySql server to perform MYSQL Queries. First, we need to use the POD connection, the code is given below. Download the Database class file from here.
Once the connection is established you can perform actions on MySQL server. In convert.php paste below code that we use to convert canvas into the image and save into Database.
In the above code snippet, we create an image from data image with the help of PHP and then we save into the Database and on the server.
Html to canvas php
PHP Proxy html2canvas
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
PHP Proxy html2canvas
This script allows you to use html2canvas.js with different servers, ports and protocols (http, https), preventing to occur «tainted» when exporting the for image.
Others scripting language
You do not use PHP, but need html2canvas working with proxy, see other proxies:
Problems and solutions
When adding an image that belongs to another domain in and after that try to export the canvas for a new image, a security error occurs (actually occurs is a security lock), which can return the error:
SecurityError: DOM Exception 18
Error: An attempt was made to break through the security policy of the user agent.
If using Google Maps (or google maps static) you can get this error in console:
Google Maps API error: MissingKeyMapError
Access to Image at ‘file:///. ‘ from origin ‘null’ has been blocked by CORS policy: Invalid response. Origin ‘null’ is therefore not allowed access.
Means that you are not using an HTTP server, html2canvas does not work over the «file:///» protocol, use Apache, Nginx or IIS with PHP for work.
I ask you to follow me or «star» my repository to track updates
Run script in Cross-domain (data URI scheme)
Note: Enable cross-domain in proxy server can consume more memory, but can be faster in execution it performs only one request at the proxy server.
Note: If the file html2canvasproxy.php is in the same domain that your project, you do not need to enable this option.
Note: Disable the «cross-domain» does not mean you will not be able to capture images from different servers, in other words, the «cross-domain» here refers to «html2canvas.js» (not necessarily the javascript file, but the place where runs) and the «html2canvas.php» are in different domains, the «cross-domain» here refers domain.
In some cases you may want to use this html2canvasproxy.php on a specific server, but the «html2canvas.js» and another server, this would cause problems in your project with the security causing failures in execution. In order to use security just set in the html2canvasproxy.php:
Enable data uri scheme for use proxy for all servers:
Rendering HTML elements to
Is there a way to have an arbitrary HTML element rendered in a canvas (and then access its buffer. ).
6 Answers 6
You won’t get real HTML rendering to per se currently, because canvas context does not have functions to render HTML elements.
There are some emulations:
html2canvas project http://html2canvas.hertzen.com/index.html (basically a HTML renderer attempt built on Javascript + canvas)
HTML to SVG to might be possible depending on your use case:
Also if you are using Firefox you can hack some extended permissions and then render a DOM window to
It will render html element using creating SVG images.
For Example: There is I like cheese HTML element. And I want to add it into Canvas Element.
Here is Javascript Code to add HTML element to canvas.
Here is code to render arbitrary HTML into a canvas:
The CSS element() function may eventually help some people here, even though it’s not a direct answer to the question. It allows you to use an element (and all children, including videos, cross-domain iframes, etc.) as a background image (and anywhere else that you’d normally use url(. ) in your CSS code). Here’s a blog post that shows what you can do with it.
It has been implemented in Firefox since 2011, and is being considered in Chromium/Chrome (don’t forget to give the issue a star if you care about this functionality).
If you need to access the canvas then you can use html2canvas
I am trying to find another project as html2canvas is very slow in performance
According to the HTML specification you can’t access the elements of the Canvas. You can get its context, and draw in it manipulate it, but that is all.
If the element doesn’t shows up, maybe the canvas is before it, so use the z-index CSS property to bring it before the canvas.
CANVAS шаг за шагом: Основы
Предварительная «настройка» нашего холста
У нашего подопытного тега есть всего два атрибута — height и width, высота и ширина соответственно, по умолчанию размер холста 150х300 пикселей.
Стоит отметить что canvas создает область фиксированного размера содержимым которого управляют контексты.
Элементарный пример:
Если сохранить эти несчастные 13 строк в файл и открыть его браузером, то можно будет увидеть область с чёрным прямоугольником, так вот это и есть тот самый холст, на котором нарисован прямоугольник размеры которого равны размерам canvas’а.
Прямоугольники
Самой элементарной фигурой которую можно рисовать является прямоугольник. Предусмотрено три функции для отрисовки прямоугольников.
Пример иллюстрирующий работу этих функций:
А теперь краткий построчный разбор:
в строках 10 и 11 мы изменили размер холста — чтоб бы задуманное нами изображение полностью отобразилось,
в строках 12 и 13 мы нарисовали два не закрашенных прямоугольника которые будут символизировать своеобразную рамку нашей «шахматной доски»,
в строке 14 отрисовываем закрашенный прямоугольник размеры которого бы позволил вместить в себе 64 квадрата с шириной стороны 32 пикселя,
в строках с 15 по 19 у нас работает два цикла которые очищают на чёрном прямоугольнике квадратные области в таком порядке что бы в итоге полученное изображение было похоже на шахматную доску
Линии и дуги
Рисование фигур составленных из линий выполняется последовательно в несколько шагов:
beginPath используется что бы «начать» серию действий описывающих отрисовку фигуры. Каждый новый вызов этого метода сбрасывает все действия предыдущего и начинает «рисовать» занова.
closePath является не обязательным действием и по сути оно пытается завершить рисование проведя линию от текущей позиции к позиции с которой начали рисовать.
Завершающий шаг это вызовом метода stroke или fill. Собственно первый обводит фигуру линиями, а второй заливает фигуру сплошным цветом.
Те кто когда-то на школьных 486х в былые годы рисовал в бейсике домик, забор и деревце по задумке учителя тот сразу поймёт часть ниже. Итак, существуют такие методы как,
Пример ниже показывает действие всего описанного выше:
В строке 14 заливается цветом дуга, в строке 22 обводится контур нашей короны.
Кривые Бернштейна-Безье
Что такое кривые Безье я думаю лучше объяснит Википедия.
Нам доступно две функции, для построения кубической кривой Бизье и квадратичной, соотвестствено:
x и y это точки в которые необходимо перейти, а координаты P(Px, Py) в квадратичной кривой это дополнительные точки которые используются для построения кривой. В кубическо кривой соответственно две дополнительные точки.
Пример двух кривых:
Добавим цвета
Что бы наше изображение было не только двух цветов, а любого цвета предусмотрено, два свойства
Цвет задается точно так же как и css, на примере все четыре способа задания цвета
Аналогично задаётся и цвет для линий.
Возьмём пример с шахматной доской и добавим в него немного цвета:
Задача
Что бы усвоить информацию и закрепить прочитанное на практике я всегда ставлю перед собой не большую цель которая бы одновременно охватывала всё прочитанное и одновременно процесс достижения которой было бы интересен мне самому. В данном случае я попытаюсь отрисовать уровень одной из моих самых любимых в детстве игр. Собственно за не имением времени — добавлять жизнь на него я не буду, а сделаю максимально понятный код охватывающий практически всё то что сегодня здесь описал.
Я воспроизвел один из уровней игры BattleCity известную у нас как Танчики, а вот и ссылка на pastebin на случай если не будет откликаться дропбокс.
На последок комментарий по примеру. В спецификациях картинки которую может выдавать Денди разрешение экрана должно быть 256×240 пикселей.
Поле боя в общеизвестнных Танчиках размером 13х13 больших блоков. Каждый из которых нарисован 4мя повторяющимися спрайтами (коих по общему подсчёту выходит на карте 26х26=676). Итак прикинем как было в оригинале по пикселам и как это правильно масштабировать. Если поделить 240 на 26 то выйдет что целая часть от деления будет 8. Получается что размерность текстуры была 8х8 пиксела т.е. размер поля боя 208х208, а большого блока 16х16. Ширина должна быть 256 пикселов. Сейчас вычислим размер правого столбца с дополнительной информацией и размер полей сверху/снизу. Справа если присмотреться ширина составляет размерность в два блока, итого 2*16=32. У нас уже 32+208=240 слева поле 16, а снизу и сверху соответственно так же по 16 пикселов. Собственно в моём примере размерность большого блока заключена в переменной cellSize, собственно все вычисления делаются иходя из её размеров. Можете по экспериментировать и поменять её значение, настоятельно рекомендую делать его кратным степеням двойки (16, 32, 64, 128. ), если хотите чтоб всё выглядело так как на старом добром денди то устанавливайте её значение равным 16. Хотя и при любых других значениях всё выглядит нормально. Если то как я пишу понравится кому-то кроме меня, то напишу продолжение, а то что в нём будет пока утаю