我正在尝试有一个跟随鼠标的svg,我试图使用.drawImage来获取所需的内容,但我不明白为什么'var img = new Image(); '是错误的变量,错误在哪里? If而不是新的image变量,我使用ctx.createRadialGradient来获得所需的图像,但是没有image时,我在javascript上是新手,因此对技巧和批评表示赞赏! :)
$(document).ready(function(e) {
$(document).mousemove(function(e) {
var canvas = document.querySelector('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var can = document.getElementById('canvas');
ctx = canvas.getContext('2d'),
var img = new Image();
img.src = "https://svgshare.com/i/LDY.sfsvg";
img.onload = function() {
var imgW = img.naturalWidth || canvasW, imgH = img.naturalHeight || canvasH;
var ratio = canvasW/imgW;
console.log(imgW, imgH, canvasW, canvasH);
ctx.drawImage(img, 0, 0, imgW * ratio, imgH*ratio);
}
});
});
body, html {
margin: 0px;
padding: 0px;
overflow: hidden;
background-color: purple;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<canvas >
</canvas>
问题是在声明ctx之后缺少分号
var can = document.getElementById('canvas');
ctx = canvas.getContext('2d');
var img = new Image();
img.src = "https://svgshare.com/i/LDY.sfsvg";
另一个是,您永远不会定义这些变量canvasW,canvasH