【问题标题】:draw svg file on html canvas programmatically以编程方式在 html 画布上绘制 svg 文件
【发布时间】:2019-11-14 21:34:25
【问题描述】:

我在使用 javascript 将 svg 绘制到画布上时遇到了一些麻烦。我希望这个工作...... HTML

<canvas class="buttonCanvas" id="handCanvas" height="60px" width="60px"  />

Javascript

function drawHandCanvas(){
   var canvas = document.getElementById('handCanvas');
   var ctx = canvas.getContext('2d');
   var img=  document.createElement('img');
   img.src='images/handCursor.svg';
   img.width = 60;  img.height = 60;
   ctx.drawImage(img,0,0);
}
drawHandCanvas();

但事实并非如此。

如果我添加一个 SVG 元素,我可以让它工作。 HTML

<canvas class="buttonCanvas" id="handCanvas" height="60px" width="60px"  />
<img id="handSVG" src="images/handCursor.svg"/>

Javascript

function drawHandCanvas(){
    var canvas = document.getElementById('handCanvas');
    var ctx = canvas.getContext('2d');
    var img=document.getElementById('handSVG');
    img.width = 60; img.height = 60;    
    setTimeout(function(){
        ctx.drawImage(img,0,0);
        img.hidden='true';
    }, 10);         
}
drawHandCanvas();

请注意,在第二种方法中,我必须使用 setTimeout 方法才能使其工作,并在我的 down 末尾添加一个 img 元素,我在画布上绘制后将其隐藏。超级哈克!如果我只使用 window.onload 而不是 setTimeout,它就不起作用。它将隐藏 img,但 drawImage() 什么也不做,大概是因为当窗口已经完成加载时画布还没有准备好。有什么想法吗?

【问题讨论】:

    标签: html canvas svg


    【解决方案1】:

    我没有您的 svg 文件,但话虽如此,您通常必须等到图像加载后才能加载到画布上。这就像画一些不存在的东西。我认为这应该适合你。

    function drawHandCanvas(){
       var canvas = document.getElementById('handCanvas');
       var ctx = canvas.getContext('2d');
       var img=  document.createElement('img');
    
       img.onload = function(){
        ctx.drawImage(this,0,0);
       }
    
        img.src='images/handCursor.svg';
        img.width = 60;  img.height = 60;
    
    }
    drawHandCanvas();
    

    【讨论】:

    • 请注意img.widthimg.height 是只读的。要绘制不同的尺寸,请将尺寸移动到drawImage(this, 0, 0, 60, 60);
    猜你喜欢
    • 1970-01-01
    • 2019-08-14
    • 2017-03-03
    • 2013-01-07
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2012-01-31
    相关资源
    最近更新 更多