以编程方式在html画布上绘制svg文件

hon*_*let 2 html svg canvas

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

<canvas class="buttonCanvas" id="handCanvas" height="60px" width="60px"  />
Run Code Online (Sandbox Code Playgroud)

使用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();
Run Code Online (Sandbox Code Playgroud)

但事实并非如此.

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

<canvas class="buttonCanvas" id="handCanvas" height="60px" width="60px"  />
<img id="handSVG" src="images/handCursor.svg"/>
Run Code Online (Sandbox Code Playgroud)

使用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();
Run Code Online (Sandbox Code Playgroud)

请注意,在第二种方法中,我必须使用setTimeout方法使其工作,并在我的向下结束时添加一个img元素,我在画布上绘制后隐藏它.超级hacky!如果我只使用window.onload而不是setTimeout,它就不起作用.它将隐藏img,但drawImage()不执行任何操作,可能是因为当窗口已经完成加载时画布尚未就绪.有什么想法吗?

shi*_*ird 7

我没有你的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();
Run Code Online (Sandbox Code Playgroud)

  • 请注意,`img.width`和`img.height`是只读的.要绘制不同的大小,请将大小移动到`drawImage(this,0,0,60,60);` (3认同)