简体   繁体   English

SVG 到画布图像工作一半时间

[英]SVG to canvas Image working half of the time

I want to compare two svg paths (user and model) at some point.我想在某个时候比较两个 svg 路径(用户和模型)。 The idea is to transform each of them onto ImageData to be able to make pixel comparisons.这个想法是将它们中的每一个转换为 ImageData 以便能够进行像素比较。 The problem I have is using the drawImage which leads me to an empty canvas half of the time.我遇到的问题是使用 drawImage 导致我有一半时间使用空画布。

let modelCanvas = document.createElement("canvas");
let modelContext = modelCanvas.getContext("2d");
modelCanvas.width = 898;
    modelCanvas.height = 509;
document.body.appendChild(modelCanvas);
let modelImg = new Image(898, 509);
modelImg.src = 'data:image/svg+xml;base64,PHN2ZyBjbGFzcz0ic3ZnLW[....]';
modelContext.drawImage(modelImg, 0, 0, 898, 509);

The code is pretty straightforward and always run without producing error.代码非常简单,并且始终运行而不会产生错误。 Still drawImage seems to fail silently times to times.仍然 drawImage 似乎多次默默地失败。

Here is the JSFiddle (with the full data string) : https://jsfiddle.net/Ldgpuo03/这是 JSFiddle(带有完整数据字符串): https ://jsfiddle.net/Ldgpuo03/

Thank you very much for your help.非常感谢您的帮助。

Image loading by web browser is an asynchronous operation. Web 浏览器加载图像是一种异步操作。

You are trying to call modelContext.drawImage when the image is not guaranteed to be loaded.当无法保证加载图像时,您正在尝试调用modelContext.drawImage

You must place your drawing code inside the image.onload callback function您必须将绘图代码放在image.onload回调函数中

This function will be called once when the image loading is fully finished.该函数将在图像加载完全完成后调用一次。

 let modelCanvas = document.createElement("canvas"); let modelContext = modelCanvas.getContext("2d"); modelCanvas.width = 40; modelCanvas.height = 40; document.body.appendChild(modelCanvas); let modelImg = new Image(); modelImg.src = 'https://i.stack.imgur.com/EK1my.png?s=48'; modelImg.onload = function(){ modelContext.drawImage(modelImg, 0, 0, 40, 40); }

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

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