简体   繁体   English

读 <img> 画布样式(html5,js)

[英]Reading <img> style to Canvas (html5,js)

I have a canvas where the user make interactions, then a <img> for the final "product". 我有一个供用户进行交互的画布,然后是最后一个“产品”的<img> The <img> tag has the style properly filled with the data URI of the first canvas. <img>标签的样式正确填充了第一个画布的数据URI。

I now need to fetch this "canvas" as a element then transform it into a canvas object. 现在,我需要获取此“画布”作为元素,然后将其转换为画布对象。 Example: 例:

var canvas = parent.document.getElementById('canvas_holder');
var context = canvas.getContext("2d");
context.strokeStyle = '#f00';
//etc... 

*canvas_holder* is the <img> tag with style set to real canvas data URI. * canvas_holder *是<img>标签,其样式设置为实际的画布数据URI。 How would I go to make this thinking work? 我将如何使这种思维发挥作用? I can not change the structure of the <img> , unfortunately. 不幸的是,我无法更改<img>的结构。

Appreciate any help! 感谢任何帮助!

You don't need to mess with the base64-encoded version of the image. 您无需弄混该图像的base64编码版本。 Just use 只需使用

var img = document.getElementById('myImage'); // your <img>   

var can = document.getElementById('myCanvas'); // your <canvas>
can.width = img.width;
can.height = img.height;
var ctx = can.getContext('2d');

ctx.drawImage(img, 0, 0, img.width, img.height); // draw the image onto the canvas

This should draw the image onto the canvas. 这应该将图像绘制到画布上。

I think the OP wants to tell us that the image is a combination of a foreground image transparent.png and a background image which is represented by its base64 encoded version. 我认为OP希望告诉我们该图像是前景图像transparent.png和背景图像的组合,该背景图像由其base64编码版本表示。 The only way I see is to grab the background image from 我看到的唯一方法是从抓住背景图片

var image = new Image();
image.src = $('#canvas_holder').css('background-image').match(/url\("?'?(.*)"?'?\)/)[1];
//  If you don't want to use jQuery, you could get the background-image as
// image.src = document.getElementById('canvas_holder').style.backgroundImage.match(/url\("?'?(.*)"?'?\)/)[1];

and paste it onto the canvas. 并将其粘贴到画布上。

var canvas = document.getElementById('yourcanvasid');
var ctx = canvas.getContext('2d');
ctx.drawImage(image, 0, 0);

and then get the foreground image and paste it onto the same canvas 然后拿到前景图像并将其粘贴到画布一样

var foreGround = document.getElementById('canvas_holder');
ctx.drawImage(foreGround, 0, 0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM