Drawing an SVG file on a HTML5 canvas - html

Is there a default way of drawing an SVG file onto a HTML5 canvas? Google Chrome supports loading the SVG as an image (and simply using drawImage), but the developer console does warn that resource interpreted as image but transferred with MIME type image/svg+xml.
I know that a possibility would be to convert the SVG to canvas commands (like in this question), but I'm hoping that's not needed. I don't care about older browsers (so if FireFox 4 and IE 9 will support something, that's good enough).

EDIT: Dec 2019
The Path2D() constructor is supported by all major browsers now, "allowing path objects to be declared on 2D canvas surfaces".
EDIT: Nov 2014
You can now use ctx.drawImage to draw HTMLImageElements that have a .svg source in some but not all browsers (75% coverage: Chrome, IE11, and Safari work, Firefox works with some bugs, but nightly has fixed them).
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
}
img.src = "http://upload.wikimedia.org/wikipedia/commons/d/d2/Svg_example_square.svg";
Live example here. You should see a green square in the canvas. The second green square on the page is the same <svg> element inserted into the DOM for reference.
You can also use the new Path2D objects to draw SVG (string) paths. In other words, you can write:
var path = new Path2D('M 100,100 h 50 v 50 h 50');
ctx.stroke(path);
Live example of that here.
Original 2010 answer:
There's nothing native that allows you to natively use SVG paths in canvas. You must convert yourself or use a library to do it for you.
I'd suggest looking in to canvg: (check homepage & demos)
canvg takes the URL to an SVG file, or the text of the SVG file, parses it in JavaScript and renders the result on Canvas.

Further to #Matyas answer: if the svg's image is also in base64, it will be drawn to the output.
Demo:
var svg = document.querySelector('svg');
var img = document.querySelector('img');
var canvas = document.querySelector('canvas');
// get svg data
var xml = new XMLSerializer().serializeToString(svg);
// make it base64
var svg64 = btoa(xml);
var b64Start = 'data:image/svg+xml;base64,';
// prepend a "header"
var image64 = b64Start + svg64;
// set it as the source of the img element
img.onload = function() {
// draw the image onto the canvas
canvas.getContext('2d').drawImage(img, 0, 0);
}
img.src = image64;
svg, img, canvas {
display: block;
}
SVG
<svg height="40" width="40">
<rect width="40" height="40" style="fill:rgb(255,0,255);" />
<image xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAEX0lEQVQ4jUWUyW6cVRCFv7r3/kO3u912nNgZgESAAgGBCJgFgxhW7FkgxAbxMLwBEmIRITbsQAgxCEUiSIBAYIY4g1EmYjuDp457+Lv7n+4tFjbwAHVOnVPnlLz75ht67OhhZg/M0p6d5tD9C8SNBBs5XBJhI4uNLC4SREA0UI9yJr2c4e6QO+v3WF27w+rmNrv9Pm7hxDyHFg5yYGEOYxytuRY2SYiSCIwgRgBQIxgjEAKuZWg6R9S0SCS4qKLZElY3HC5tp7QPtmlMN7HOETUTXBJjrEGsAfgPFECsQbBIbDGJZUYgGE8ugQyPm+o0STtTuGZMnKZEjRjjLIgAirEOEQEBDQFBEFFEBWLFtVJmpENRl6hUuFanTRAlbTeZarcx0R6YNZagAdD/t5N9+QgCYAw2jrAhpjM3zaSY4OJGTDrVwEYOYw2qioigoviq5MqF31m9fg1V5fCx+zn11CLNVnufRhBrsVFE1Ihpthu4KDYYwz5YQIxFBG7duMZnH31IqHL6wwnGCLFd4pez3/DaG2/x4GNPgBhEZG/GGlxkMVFkiNMYay3Inqxed4eP33uf7Y0uu90xWkGolFAru7sZn5w5w921m3u+su8vinEO02hEWLN/ANnL2rkvv2an2yd4SCKLM0JVBsCgAYZZzrnPP0eDRzXgfaCuPHXwuEYjRgmIBlQVVLl8/hKI4fRzz3L6uWe5+PMvnHz6aa4uX+D4yYe5vXaLH86eoyoLjLF476l9oKo9pi5HWONRX8E+YznOef7Vl1h86QWurlwjbc+QpikPPfoIcZLS39pmMikp8pzae6q6oqgriqrGqS+xeLScoMYSVJlfOMTl5RXW1+5w5fJVnFGWf1/mxEMnWPppiclkTLM5RdJoUBYFZVlQ5DnZMMMV167gixKLoXXsKGqnOHnqOJ/+/CfZ+XUiZ0jTmFv5mAvf/YjEliQ2vPD8Ir6qqEcZkzt38cMRo5WruFvfL9FqpyRxQhj0qLOax5I2S08+Tu/lFiGUGOPormxwuyfMnjrGrJa88uIixeYWl776lmrzNjmw8vcG8sU7ixpHMXFsCUVg9tABjEvRgzP82j7AhbyiX5Qcv2+Bvy7dYGZ1k7efeQB/Y4PBqGBtdYvb3SFzLcfqToZc/OB1zYeBSpUwLBlvjZidmWaSB1yaYOfn6LqI/r0hyU6P+cRSlhXjbEI2zvnt7y79oqQ3qeg4g6vKjCIXehtDmi6m0UnxVnCRkPUHVNt9qkLJxgXOCYNOg34v48raPaamU2o89/KKsQ9sTSpc0JK7NwdcX8s43Ek5cnSOLC/Z2R6Rj0ra0w2W1/t0xyWn51uk2Ri1QtSO6OU5d7OSi72cQeWxKG7p/Dp//JXTy6C1Pcbc6DMpPRtjTxChEznWhwVZUCKrjCrPoPDczHLmnLBdBgZlRRWUEBR3ZKrme5TlrTGlV440Y1IrXM9qQGi6mkG5V6uza7tUIeCDElTZ1L26elX+fcH/ACJBPYTJ4X8tAAAAAElFTkSuQmCC" height="20px" width="20px" x="10" y="10"></image></svg><br/>
IMAGE
<img/><br/>
CANVAS
<canvas></canvas><br/>

You can easily draw simple svgs onto a canvas by:
Assigning the source of the svg to an image in base64 format
Drawing the image onto a canvas
Note: The only drawback of the method is that it cannot draw images embedded in the svg. (see demo)
Demonstration:
(Note that the embedded image is only visible in the svg)
var svg = document.querySelector('svg');
var img = document.querySelector('img');
var canvas = document.querySelector('canvas');
// get svg data
var xml = new XMLSerializer().serializeToString(svg);
// make it base64
var svg64 = btoa(xml);
var b64Start = 'data:image/svg+xml;base64,';
// prepend a "header"
var image64 = b64Start + svg64;
// set it as the source of the img element
img.src = image64;
// draw the image onto the canvas
canvas.getContext('2d').drawImage(img, 0, 0);
svg, img, canvas {
display: block;
}
SVG
<svg height="40">
<rect width="40" height="40" style="fill:rgb(255,0,255);" />
<image xlink:href="https://en.gravatar.com/userimage/16084558/1a38852cf33713b48da096c8dc72c338.png?size=20" height="20px" width="20px" x="10" y="10"></image>
</svg>
<hr/><br/>
IMAGE
<img/>
<hr/><br/>
CANVAS
<canvas></canvas>
<hr/><br/>

Mozilla has a simple way for drawing SVG on canvas called "Drawing DOM objects into a canvas"

As Simon says above, using drawImage shouldn't work. But, using the canvg library and:
var c = document.getElementById('canvas');
var ctx = c.getContext('2d');
ctx.drawSvg(SVG_XML_OR_PATH_TO_SVG, dx, dy, dw, dh);
This comes from the link Simon provides above, which has a number of other suggestions and points out that you want to either link to, or download canvg.js and rgbcolor.js. These allow you to manipulate and load an SVG, either via URL or using inline SVG code between svg tags, within JavaScript functions.

Something to add, to show the svg correctly in canvas element add the attributes height and width to svg root element, Eg:
<svg height="256" width="421">...</svg>
Or
// Use this if to add the attributes programmatically
const svg = document.querySelector("#your-svg");
svg.setAttribute("width", `${width}`);
svg.setAttribute("height", `${height}`);
For more details see this

As vector graphics are meant to be potentially scaled, I will offer a method I have made that is as similar to SVG as possible. This method supports:
A resizable canvas
Transparency
Hi-resolution graphics (automatically, but no pinch support yet)
Scaling of the SVG in both directions! (To do this with pixels, you will have to divide the new length by the old one)
This is done by converting the SVG to canvas functions here, then adding that to svgRed() (after changing the name of ctx to ctx2. The svgRed() function is used on startup and during pixel ratio changes (for example, increasing the zoom), but not before the canvas is scaled (in order to increase the size of the image). It converts the result into an Image, and can be called any time by ctx.drawImage(redBalloon, Math.round(Math.random() * w), Math.round(Math.random() * h)). To clear the screen, use ctx.clearRect(0, 0, w, h) to do so.
Testing this with the SVG, I found that this is many times faster, as long as the zoom is not set to large values (I discovered that a window.devicePixelRatio of 5 gives just over twice the speed as an SVG, and a window.devicePixelRatio of 1 is approximately 60 times faster).
This also has the bonus benefit of allowing many "fake SVG" items to exist simultaneously, without messing with the HTML (this is shown in the code below). If the screen is resized or scaled, you will need to render it again (completely ignored in my example).
The canvas showing the result is scaled down (in pixels) by the devicePixelRatio, so be careful when drawing items! Scaling (with ctx.scale() this canvas will result in a potentially blurry image, so be sure to account for the pixel difference!
NOTE: It seems that the browser takes a while to optimize the image after the devicePixelRatio has changed (around a second sometimes), so it may not be a good idea to spam the canvas with images immediately, as the example shows.
<!DOCTYPE html>
<html>
<head lang="en">
<title>Balloons</title>
<style>
* {
user-select: none;
-webkit-user-select: none;
}
body {
background-color: #303030;
}
</style>
</head>
<body>
<canvas id="canvas2" style="display: none" width="0" height="0"></canvas>
<canvas id="canvas"
style="position: absolute; top: 20px; left: 20px; background-color: #606060; border-radius: 25px;" width="0"
height="0"></canvas>
<script>
// disable pinches: hard to implement resizing
document.addEventListener("touchstart", function (e) {
if (e.touches.length > 1) {
e.preventDefault()
}
}, { passive: false })
document.addEventListener("touchmove", function (e) {
if (e.touches.length > 1) {
e.preventDefault()
}
}, { passive: false })
// disable trackpad zooming
document.addEventListener("wheel", e => {
if (e.ctrlKey) {
e.preventDefault()
}
}, {
passive: false
})
// This is the canvas that shows the result
const canvas = document.getElementById("canvas")
// This canvas is hidden and renders the balloon in the background
const canvas2 = document.getElementById("canvas2")
// Get contexts
const ctx = canvas.getContext("2d")
const ctx2 = canvas2.getContext("2d")
// Scale the graphic, if you want
const scaleX = 1
const scaleY = 1
// Set up parameters
var prevRatio, w, h, trueW, trueH, ratio, redBalloon
function draw() {
for (var i = 0; i < 1000; i++) {
ctx.drawImage(redBalloon, Math.round(Math.random() * w), Math.round(Math.random() * h))
}
requestAnimationFrame(draw)
}
// Updates graphics and canvas.
function updateSvg() {
var pW = trueW
var pH = trueH
trueW = window.innerWidth - 40
trueH = Math.max(window.innerHeight - 40, 0)
ratio = window.devicePixelRatio
w = trueW * ratio
h = trueH * ratio
if (trueW === 0 || trueH === 0) {
canvas.width = 0
canvas.height = 0
canvas.style.width = "0px"
canvas.style.height = "0px"
return
}
if (trueW !== pW || trueH !== pH || ratio !== prevRatio) {
canvas.width = w
canvas.height = h
canvas.style.width = trueW + "px"
canvas.style.height = trueH + "px"
if (prevRatio !== ratio) {
// Update graphic
redBalloon = svgRed()
// Set new ratio
prevRatio = ratio
}
}
}
window.onresize = updateSvg
updateSvg()
draw()
// The vector graphic (you may want to manually tweak the coordinates if they are slightly off (such as changing 25.240999999999997 to 25.241)
function svgRed() {
// Scale the hidden canvas
canvas2.width = Math.round(44 * ratio * scaleX)
canvas2.height = Math.round(65 * ratio * scaleY)
ctx2.scale(ratio * scaleX, ratio * scaleY)
// Draw the graphic
ctx2.save()
ctx2.beginPath()
ctx2.moveTo(0, 0)
ctx2.lineTo(44, 0)
ctx2.lineTo(44, 65)
ctx2.lineTo(0, 65)
ctx2.closePath()
ctx2.clip()
ctx2.strokeStyle = '#0000'
ctx2.lineCap = 'butt'
ctx2.lineJoin = 'miter'
ctx2.miterLimit = 4
ctx2.save()
ctx2.beginPath()
ctx2.moveTo(0, 0)
ctx2.lineTo(44, 0)
ctx2.lineTo(44, 65)
ctx2.lineTo(0, 65)
ctx2.closePath()
ctx2.clip()
ctx2.save()
ctx2.fillStyle = "#e02f2f"
ctx2.beginPath()
ctx2.moveTo(27, 65)
ctx2.lineTo(22.9, 61.9)
ctx2.lineTo(21.9, 61)
ctx2.lineTo(21.1, 61.6)
ctx2.lineTo(17, 65)
ctx2.lineTo(27, 65)
ctx2.closePath()
ctx2.moveTo(21.8, 61)
ctx2.lineTo(21.1, 60.5)
ctx2.bezierCurveTo(13.4, 54.2, 0, 41.5, 0, 28)
ctx2.bezierCurveTo(0, 9.3, 12.1, 0.4, 21.9, 0)
ctx2.bezierCurveTo(33.8, -0.5, 45.1, 10.6, 43.9, 28)
ctx2.bezierCurveTo(43, 40.8, 30.3, 53.6, 22.8, 60.2)
ctx2.lineTo(21.8, 61)
ctx2.fill()
ctx2.stroke()
ctx2.restore()
ctx2.save()
ctx2.fillStyle = "#f59595"
ctx2.beginPath()
ctx2.moveTo(18.5, 7)
ctx2.bezierCurveTo(15.3, 7, 5, 11.5, 5, 26.3)
ctx2.bezierCurveTo(5, 38, 16.9, 50.4, 19, 54)
ctx2.bezierCurveTo(19, 54, 9, 38, 9, 28)
ctx2.bezierCurveTo(9, 17.3, 15.3, 9.2, 18.5, 7)
ctx2.fill()
ctx2.stroke()
ctx2.restore()
ctx2.restore()
ctx2.restore()
// Save the results
var image = new Image()
image.src = canvas2.toDataURL()
return image
}
</script>
</body>
</html>

Try this:
let svg = `<svg xmlns="http://www.w3.org/2000/svg" ...`;
let blob = new Blob([svg], {type: 'image/svg+xml'});
let url = URL.createObjectURL(blob);
const ctx = canvas.getContext('2d');
canvas.width = 900;
canvas.height = 1400;
const appLogo = new Image();
appLogo.onload = () => ctx.drawImage(appLogo, 54, 387, 792, 960);
appLogo.src = url;
// let image = document.createElement('img');
// image.src = url;
// image.addEventListener('load', () => URL.revokeObjectURL(url), {once: true});
Note: Blob is not defined in Node.js file, This is code designed to run in the browser, not in Node.
More info here

Related

HTML5 - scaled image is blurry when drawn on canvas in chrome & opera

When i draw scaled image on canvas using the drawImage() function it looks slightly blurry in Chrome & Opera, but if i draw the full size image first and then the scaled one it looks crisp. What causes the blurriness and how can i fix it?
Here is the original image:
Here is the result in Chrome & Opera:
const img = new Image();
const crisptCanvas = document.getElementById('crisp-canvas');
const crispContext = crisptCanvas.getContext('2d');
const blurryCanvas = document.getElementById('blurry-canvas');
const blurryContext = blurryCanvas.getContext('2d');
const sx = 0, sy = 0, sWidth = 1980, sHeight = 1251;
const dx = 0, dy = 0;
const scaleFactor = 0.4762626262626263;
// Draw an image on canvas
function scaleImage(scale, context)
{
const dWidth = (sWidth*scale);
const dHeight = (sHeight*scale);
context.drawImage(img, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
};
// When image is loaded draw it on both canvases
img.onload = function(){
// First draw the source image in full scale and then using the -scaleFactor
setTimeout(()=> {
scaleImage(1, crispContext);
scaleImage(scaleFactor, crispContext);
}, 0);
// Draw the image using the -scaleFactor
scaleImage(scaleFactor, blurryContext);
}
img.src = "https://i.stack.imgur.com/eWDSw.png"
<canvas width="944" height="596" id="crisp-canvas" ></canvas>
<canvas width="944" height="596" id="blurry-canvas" ></canvas>
Well after one day trying everything i can think of, i was not able to find a solution when i draw the scaled image on canvas.
Here are some of the things i have tried:
1) I have tried using the scale() method, but results were the same.
2) I have tried setting the imageSmoothingEnabled property, that work well with pixelated art games, but for high resolution images the quality was awful.
3) I have tried using the window.requestAnimationFrame() method than on the first request draw the full scale image, on hidden canvas and after that draw the scaled image on my main canvas. That work well, but when i change the tab(focus on another tab), after a few minutes the images on my main canvas became blurry again. Then i added a method to check when the user focus on my tab, using the Page Visibility API, and again redraw the full scale image on the hidden canvas, but that did not work. Only the last drawn image on the hidden canvas was crisp and all images drawn before the last one were blurry. So the only solution was to create hidden canvases for each image and that is not practical, so i had to try another approach.
So here is the solution came up with:
1) Set width and height canvas properties to my original image size 1980x1251
2) I scaled the canvas, using its style width & height properties
Have in mind that using this method everything drawn on the canvas like shapes, text, lines... will also be scaled. So for example if you draw a rectangle (10x10) pixels. It will have width and height each equal to 10px, only when the canvas width & height style properties match the canvas width & height properties.
canvas.style.width = canvas.width + 'px';
canvas.style.height = canvas.height + 'px';
const img = new Image();
const crispCanvas = document.getElementById('crisp-canvas');
const crispContext = crispCanvas.getContext('2d');
const sx = 0, sy = 0, sWidth = 1980, sHeight = 1251;
const dx = 0, dy = 0;
const scaleFactor = 0.4762626262626263;
// Set crisp canvas width & height properties to match the source image
crispCanvas.width = sWidth;
crispCanvas.height = sHeight;
// Scale the source canvas using width & height style properties
function scaleCanvas(scale, canvas) {
const dWidth = (sWidth*scale);
const dHeight = (sHeight*scale);
canvas.style.width = dWidth + 'px';
canvas.style.height = dHeight + 'px';
}
// When image is loaded, scale the crisp canvas and draw the full size image
img.onload = function(){
scaleCanvas(scaleFactor, crispCanvas);
crispContext.drawImage(img, sx, sy);
}
img.src = "https://i.stack.imgur.com/eWDSw.png";
<canvas id="crisp-canvas" ></canvas>

HTML canvas image is fading out after multiple iterations/reusing

I have a portal which is used for collecting orders from users in hand written format.
In my portal, I am using HTML canvas for getting inputs from user.
Once the user write order and submits it, I will read the drawings from the canvas and saves it into my DB.
HTML
<canvas height="750" width="768" id="userNotes"></canvas>
Javascript
var canvas = document.getElementById('userNotes');
var notesDataURL = canvas.toDataURL();
saveImageDataToDataBase (notesDataURL);
Next time when the user comes for a new order, I will draw this image back into the canvas, so that he can make modifications on the same and submit it as fresh order.
Javascript
var canvas = document.getElementById('userNotes');
var context = canvas.getContext('2d');
var img = new Image();
img.src = imageData;
context.drawImage(img, 0, 0);
Problem that I am facing is that after multiple iterations, the image starts fading out.
One observation is that fading is more at the bottom part of the image and less on the top side.
Consider the below sample images,
After 10 iterations image became like this,
Below is a JS FIddle created using sample code, in this after about 25 iterations fading will be visible(issue is visible only in tablet mentioned below).
https://jsfiddle.net/hz8r993v/
Observation:
An observation which I made is the issue is happening only in a specific tablet model, Samsung SM-P550, which is unfortunately the one my application is build for.
I am not able to reproduce this issue while using this application in my laptop, PC or another sm-p650 tablet.
Currently Only happening in all tablets of model SM-P550. Even I am confused with this observation.
I also tried disabling ImageSmoothingEnabled properties, but not helping.
Any leads/clues are appreciated.
JPEG compression quirk & rounding.
Looking at the image you provided suggests to me that you are incorrectly offsetting the image each time you render it. As you have not provided enough code for anyone to make an assessment as to why this is happening leaves us only to guess.
Lossless JPEG!
My first instinct is that you have offset the drawing or scaled it. I create the example below and offset a jpeg url of the rendered text by 0.2 pixels.
The result no blur Not a real surprise Jpegs are designed so that they can be copied. The artifacts introduced by the compression actually remove the blur introduced by the offset
Draw jpeg image 0.2 pixels down save and repeat.
var ctx = canvas.getContext("2d");
ctx.font = "64px Arial";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("testing",canvas.width / 2,canvas.height / 2);
ctx.font = "18px Arial";
var count = 0;
var imgURL;
function copy(){
imgURL = canvas.toDataURL();
}
function paste(x,y){
var img = new Image;
img.src = imgURL;
img.onload = function(){
ctx.fillStyle = "white";
ctx.fillRect(0,0,canvas.width,canvas.height);
ctx.drawImage(img,x,y);
ctx.fillStyle = "red";
ctx.fillText("Copy : " + count,canvas.width / 2,count * 20);
}
}
function iterate(){
count += 1;
copy();
paste(0,0.2);
if(count < 100){
setTimeout(iterate,50);
}
}
iterate();
<canvas id="canvas" width = 300 height = 150></canvas>
Your image clearly shows a vertical blurring so I set about finding when I can blur the image so that it over comes the Jpeg compression. Offsetting by 0.5 or more does not blur the image just scrolls pixel perfect 100 pixels (note I copy past 100 times move image 0.5 pixels down yet resulting image has moved 100 pixels. I have marked row 100)
Jpeg turns 0.5 pixel steps into 1 pixel steps
var ctx = canvas.getContext("2d");
ctx.font = "64px Arial";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("testing",canvas.width / 2,canvas.height / 2);
ctx.font = "18px Arial";
var count = 0;
var imgURL;
function copy(){
imgURL = canvas.toDataURL();
}
function paste(x,y){
var img = new Image;
img.src = imgURL;
img.onload = function(){
ctx.fillStyle = "white";
ctx.fillRect(0,0,canvas.width,canvas.height);
ctx.drawImage(img,x,y);
ctx.fillStyle = "red";
ctx.fillText("Copy : " + count,canvas.width / 2,count * 20);
if(count === 100){
ctx.fillRect(0,100,canvas.width,1);
}
}
}
function iterate(){
count += 1;
copy();
paste(0,0.5);
if(count < 100){
setTimeout(iterate,50);
}
}
iterate();
<canvas id="canvas" width = 300 height = 150></canvas>
At end redline is pixel row 100.
Seams that Jpeg compression is much better at preserving the original src image pixels than I suspected. But that does not help solve the problem.
Device specific
So is it a quirk of the device. I look up the specs and nothing stands out. I begin to suspect that you may have a canvas display scaling issues (the canvas resolution not matching the display size)
I start to set up the snippet to use differing resolutions and by shear chance I run the code at the same resolution as the samsung device mentioned in the question.
Blurring yay... but i did not change the canvas pixel scaling, all I did was change the canvas resolution.
Example of blurring.
Note that offset is 0.01 pixels (100th of a pixel)
var ctx = canvas.getContext("2d");
ctx.font = "64px Arial";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("testing",canvas.width / 2,canvas.height / 2);
ctx.font = "18px Arial";
var count = 0;
var imgURL;
function copy(){
imgURL = canvas.toDataURL();
}
function paste(x,y){
var img = new Image;
img.src = imgURL;
img.onload = function(){
ctx.fillStyle = "white";
ctx.fillRect(0,0,canvas.width,canvas.height);
ctx.drawImage(img,x,y);
ctx.fillStyle = "red";
ctx.fillText("Copy : " + count,canvas.width / 2,count * 20);
}
}
function iterate(){
count += 1;
copy();
paste(0,0.01);
if(count < 100){
setTimeout(iterate,50);
}
}
iterate();
<canvas id="canvas" width = 300 height = 1023></canvas>
Possible fix.
As there is not enough code to give a complete answer the above experiments have given me enough information to make an educated guess.
The problem is specific to the resolution 1024 height. (I have tried a few other (very limited) resolutions and could not get blurring)
The blurring does not occur at that resolution if the image is rendered at the pixel boundaries.
The possible fix.
When you render the image convert the render coordinates to integers using Math.floor(coordinate) this will ensure there is no fractional offset, even very tiny offsets that should not affect the image can be amplified by the jpeg compression when the resolution is at 1024 (and maybe some other resolutions as well).
var oldImage = new Image;
oldImage.src = "old image url";
oldImage.onload = function(){
ctx.drawImage(oldImage,Math.floor(x),Math.floor(y));
}
Hope this helps.
I am probably not experienced enough to tell you what about that tablet version, or what in your HTML/Javascript could be causing this issue. I am, however, good at problem solving, and solving puzzles.
I have two possible guesses:
Is there anything in your code, which could lead to a change in the resolution? The only reason that I think this may be part of the cause, is that because the image is being redrawn on a canvas that is the same size, any change in the image size could cause the image to become slightly pixilated. and repetitive changes in the image size would only exaggerate this change.
That is probably not the sole cause. I think that there is probably an additional cause because the issue is only present on the one specific tablet version. I am not familiar with that tablet version, but is there anything about its OS or interface that could alter the file when it is saved or redisplayed?
As a side note, it would be nice if you could provide a comparison image, just to see the change.
Hope that this at least points you in the right direction.

Play video on canvas and preserve the last frame/image on canvas

I'm using the following script code to draw a video on canvas:
$("#vPlayer").on('play', function (e) {
var canvas = $('canvas')[0];
var ctx = canvas.getContext('2d');
var $this = this;
canvas.width = 640;
canvas.height = 480;
(function loop() {
if (!$this.paused && !$this.ended) {
ctx.drawImage($this, 0, 0, 640, 480);
setTimeout(loop, 1000 / 30); // drawing at 30fps
}
})();
});
The code works well, but in my case, I want to change the video source (src attribute) of the video tag every 2 mins. When I set the src attr for the video and during the loading time for the video, the canvas displays white screen. How can I preserve the last image of video and do not clear the canvas?
It is a little bit weird because, when I don't set the width and height for the canvas, the last frame is preserved, but I need to set the size.
Every time you set the size of the canvas it will be cleared.
To avoid this you need to set the size at the "beginning", before you start drawing to it. In this case I would recommend you set it outside your event handler as well as the initializing of the canvas and context variable:
var canvas = $('canvas')[0];
var ctx = canvas.getContext('2d');
canvas.width = 640;
canvas.height = 480;
$("#vPlayer").on('play', function (e) {
var $this = this;
(function loop() {
if (!$this.paused && !$this.ended) {
ctx.drawImage($this, 0, 0, 640, 480);
setTimeout(loop, 1000 / 30); // drawing at 30fps
}
})();
});

html5 getImageData then putImageData results in fading image

I'm very new to Html5 and I was wondering if someone could shed some light on this:
<script type="text/javascript">
window.onload = function () {
var canvas = document.getElementById('canvas'); //682 x 111 pixel canvas
var context = canvas.getContext('2d');
var image = new Image();
image.src = "/Content/ImageTestOne/logo-for-dissolve.png"; //682 x 111 pixel image
image.onload = function () { context.drawImage(image, 0, 0); drawFrame(); };
function drawFrame() {
window.requestAnimationFrame(drawFrame, canvas);
imageData = context.getImageData(0, 0, canvas.width, canvas.height);
//Do something to some pixels here that persists over time
context.clearRect(0, 0, canvas.width, canvas.height);
context.putImageData(imageData, 0, 0);
};
};
</script>
According to my limited knowledge of Html5 this code should do nothing except continually display the "image". But instead the image quite rapidly burns out to almost white which suggests that the imageData is changed slightly each time it is either read from or written to the canvas...
Basically I wanted to fade the image where the mouse was located so that a background image shows through as the mouse is moved around. Is there a way around this or am I going to have to become a little more creative with the process? Is there anyway I can manipulate the "image" ImageData rather than getting it from the canvas each time?
Thanks in advance, I've tried using jpg and png and loading into DOM rather than via image.src but they all have the same issue.
Using the latest Chrome btw.
Here is the setup for the requestionAnimationFrame to handle a range of browsers with a fail over to SetTimeout:
(!window.requestAnimationFrame)
{
window.requestAnimationFrame = (window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) {
return window.setTimeout(callback, 1000/60);
});
}
Here is the code for the canvas
<canvas id="canvas" width="682" height="111"></canvas>
That's all the code for this.
putImageData() and getImageData() can be lossy. There's a note in the spec about this:
Due to the lossy nature of converting to and from premultiplied alpha
color values, pixels that have just been set using putImageData()
might be returned to an equivalent getImageData() as different values.
See also this related question:
Why does HTML Canvas getImageData() not return the exact same values that were just set?
I have tried also to apply this to my game where in im going to manipulate the selected pixels to have effect but It doesn't give me the expected result
here is some sample code that i used to manipulate the pixel to change
get image information and store
var img = context.getImageData(0,0, width, height)
var imgdata = img.data
var len = imgdata.length
loop to all data and manipulate pixel information
var i = 0;
for(i; i<leng; i++) {
var red = imgdata[i]
var green = imgadata[i+1]
var blue = imgdata[i+2]
var alpha = imgdata[i+3]
imgdata[i] = new value
imgdata[i+1] = new value
imgdata[i+2] = new value
imgdata[i+3] = new value
}
context.putImageData(img, 0,0)
then create animation frame to see effect
requestAnimationFrame is an experimental feature (june 2012) that uses time based frame access. The reason for this is avoid latency in animations.
I suggest you take a look at this Moz article.

How to change the opacity (alpha, transparency) of an element in a canvas element?

Using the HTML5 <canvas> element, I would like to load an image file (PNG, JPEG, etc.), draw it to the canvas completely transparently, and then fade it in. I have figured out how to load the image and draw it to the canvas, but I don't know how to change its opacity.
Here's the code I have so far:
var canvas = document.getElementById('myCanvas');
if (canvas.getContext)
{
var c = canvas.getContext('2d');
c.globalAlpha = 0;
var img = new Image();
img.onload = function() {
c.drawImage(img, 0, 0);
}
img.src = 'image.jpg';
}
Will somebody please point me in the right direction like a property to set or a function to call that will change the opacity?
I am also looking for an answer to this question, (to clarify, I want to be able to draw an image with user defined opacity such as how you can draw shapes with opacity) if you draw with primitive shapes you can set fill and stroke color with alpha to define the transparency. As far as I have concluded right now, this does not seem to affect image drawing.
//works with shapes but not with images
ctx.fillStyle = "rgba(255, 255, 255, 0.5)";
I have concluded that setting the globalCompositeOperation works with images.
//works with images
ctx.globalCompositeOperation = "lighter";
I wonder if there is some kind third way of setting color so that we can tint images and make them transparent easily.
EDIT:
After further digging I have concluded that you can set the transparency of an image by setting the globalAlpha parameter BEFORE you draw the image:
//works with images
ctx.globalAlpha = 0.5
If you want to achieve a fading effect over time you need some kind of loop that changes the alpha value, this is fairly easy, one way to achieve it is the setTimeout function, look that up to create a loop from which you alter the alpha over time.
Some simpler example code for using globalAlpha:
ctx.save();
ctx.globalAlpha = 0.4;
ctx.drawImage(img, x, y);
ctx.restore();
If you need img to be loaded:
var img = new Image();
img.onload = function() {
ctx.save();
ctx.globalAlpha = 0.4;
ctx.drawImage(img, x, y);
ctx.restore()
};
img.src = "http://...";
Notes:
Set the 'src' last, to guarantee that your onload handler is called on all platforms, even if the image is already in the cache.
Wrap changes to stuff like globalAlpha between a save and restore (in fact use them lots), to make sure you don't clobber settings from elsewhere, particularly when bits of drawing code are going to be called from events.
Edit: The answer marked as "correct" is not correct.
It's easy to do. Try this code, swapping out "ie.jpg" with whatever picture you have handy:
<!DOCTYPE HTML>
<html>
<head>
<script>
var canvas;
var context;
var ga = 0.0;
var timerId = 0;
function init()
{
canvas = document.getElementById("myCanvas");
context = canvas.getContext("2d");
timerId = setInterval("fadeIn()", 100);
}
function fadeIn()
{
context.clearRect(0,0, canvas.width,canvas.height);
context.globalAlpha = ga;
var ie = new Image();
ie.onload = function()
{
context.drawImage(ie, 0, 0, 100, 100);
};
ie.src = "ie.jpg";
ga = ga + 0.1;
if (ga > 1.0)
{
goingUp = false;
clearInterval(timerId);
}
}
</script>
</head>
<body onload="init()">
<canvas height="200" width="300" id="myCanvas"></canvas>
</body>
</html>
The key is the globalAlpha property.
Tested with IE 9, FF 5, Safari 5, and Chrome 12 on Win7.
This suggestion is based on pixel manipulation in canvas 2d context.
From MDN:
You can directly manipulate pixel data in canvases at the byte level
To manipulate pixels we'll use two functions here - getImageData and putImageData.
getImageData usage:
var myImageData = context.getImageData(left, top, width, height);
The putImageData syntax:
context.putImageData(myImageData, x, y);
Where context is your canvas 2d context, and x and y are the position on the canvas.
So to get red green blue and alpha values, we'll do the following:
var r = imageData.data[((x*(imageData.width*4)) + (y*4))];
var g = imageData.data[((x*(imageData.width*4)) + (y*4)) + 1];
var b = imageData.data[((x*(imageData.width*4)) + (y*4)) + 2];
var a = imageData.data[((x*(imageData.width*4)) + (y*4)) + 3];
Where x is the horizontal offset, y is the vertical offset.
The code making image half-transparent:
var canvas = document.getElementById('myCanvas');
var c = canvas.getContext('2d');
var img = new Image();
img.onload = function() {
c.drawImage(img, 0, 0);
var ImageData = c.getImageData(0,0,img.width,img.height);
for(var i=0;i<img.height;i++)
for(var j=0;j<img.width;j++)
ImageData.data[((i*(img.width*4)) + (j*4) + 3)] = 127;//opacity = 0.5 [0-255]
c.putImageData(ImageData,0,0);//put image data back
}
img.src = 'image.jpg';
You can make you own "shaders" - see full MDN article here
You can. Transparent canvas can be quickly faded by using destination-out global composite operation. It's not 100% perfect, sometimes it leaves some traces but it could be tweaked, depending what's needed (i.e. use 'source-over' and fill it with white color with alpha at 0.13, then fade to prepare the canvas).
// Fill canvas using 'destination-out' and alpha at 0.05
ctx.globalCompositeOperation = 'destination-out';
ctx.fillStyle = "rgba(255, 255, 255, 0.05)";
ctx.beginPath();
ctx.fillRect(0, 0, width, height);
ctx.fill();
// Set the default mode.
ctx.globalCompositeOperation = 'source-over';
I think this answers the question best, it actually changes the alpha value of something that has been drawn already. Maybe this wasn't part of the api when this question was asked.
Given 2d context c.
function reduceAlpha(x, y, w, h, dA) {
let screenData = c.getImageData(x, y, w, h);
for(let i = 3; i < screenData.data.length; i+=4){
screenData.data[i] -= dA; //delta-Alpha
}
c.putImageData(screenData, x, y );
}
Set global Alpha draw the object that has opacity then set back to normal.
//////////////////////// circle ///////////////////////
ctx.globalAlpha = 0.75;
ctx.beginPath();
ctx.arc(x1, y1, r1, 0, Math.PI*2);
ctx.fillStyle = colour;
ctx.fill();
ctx.closePath();
ctx.globalAlpha = 1;
How i made it..on canvas i first draw rect in a selfrun function 0,0,canvas.width,canvas.height as a background of canvas and i set globalAlpha to 1 .then i draw other shapes in ather own functions and set their globalAlpha to 0.whatever number they dont affect each other even images.
Like Ian said, use c.globalAlpha = 0.5 to set the opacity, type up the rest of the settings for the square, then follow up with c.save();. This will save the settings for the square then you can c.rect and c.fillStyle the square how you want it. I chose not to wrap it with c.restore afterwards and it worked well
If you use jCanvas library you can use opacity property when drawing. If you need fade effect on top of that, simply redraw with different values.
You can't. It's immediate mode graphics. But you can sort of simulate it by drawing a rectangle over it in the background color with an opacity.
If the image is over something other than a constant color, then it gets quite a bit trickier. You should be able to use the pixel manipulation methods in this case. Just save the area before drawing the image, and then blend that back on top with an opacity afterwards.