开发者

datauri/ image to canvas

开发者 https://www.devze.com 2023-01-28 17:51 出处:网络
How do I convert an image or datauri to canvas? I see the other way at http://www.nihilogic.dk/labs/canvas2image/, but I also want to find out how I can create a canvas at the first place.

How do I convert an image or datauri to canvas? I see the other way at http://www.nihilogic.dk/labs/canvas2image/, but I also want to find out how I can create a canvas at the first place.

The reason I ask this question is because I would like to create a li开发者_开发知识库ttle app that lets user create a canvas 'image', save it as something and be able to reopen it for canvas modification in the future. I figured that datauri is a good way to save a canvas, but I am not sure how I can do to reopen the datauri and use canvas to modify the drawing.

Thanks!


Create an image element using the data URI data as the source and then use drawImage to draw it to the canvas:

var ctx = document.getElementById('ctx').getContext('2d');
var img = new Image();
img.src = uriData;
img.onload = function () {
    ctx.drawImage(img,0,0);
}

Updated: to clarify that ctx is a 2D context, not a canvas object.


I got this to work:

var img = new Image();
var uriData = "...."; // replace with dataUri

img.onload = function () {
    var ctx = document.getElementById('ctx').getContext('2d');
    ctx.drawImage(img,0,0);
}

img.src = uriData;

Looks like the trick is that the Canvas element needs its width and height specified. When I don't specify the dimensions, it becomes sort of arbitrary and it only shows part of my big image (from dataUri)

0

精彩评论

暂无评论...
验证码 换一张
取 消