第一种方法,只出现图片的左上角部分
var canvasWidth = 1152; var canvasHeight = 768; var myCanvas = document.getElementById("myCanvas"); var context; var image = new Image(); var scaleRange = document.getElementById("scaleRange"); var scale = scaleRange.value; window.onload = function() { myCanvas.width = canvasWidth; myCanvas.height = canvasHeight; if (myCanvas.getContext) { context = myCanvas.getContext("2d"); image.src = "../../images/img-lg.jpg"; image.onload = function() { //context.drawImage(image,0,0,canvasWidth,canvasHeight); drawImageByScale(scale); } } } function drawImageByScale(scale){ var scaleImageWidth = canvasWidth * scale; var scaleImageHeight = canvasHeight * scale; var sx = scaleImageWidth/2 - canvasWidth/2; var sy = scaleImageHeight/2 - canvasHeight/2; context.drawImage(image,sx,sy,canvasWidth,canvasHeight,0,0,canvasWidth,canvasHeight) }
代码里用的是老师的图,用第一种方法实现的时候将scale设置为1.0的时候只出现了图片的左上角的部分:
我个人认为这种实现方式是不是逻辑有点问题,因为image-lg.jpg的图像素本来就是canvas大小的三倍大,当将scale设置为1.0时,最后一句画图的方法是:context.drawImage(image,0,0,canvasWidth,canvasHeight,0,0,canvasWidth,canvasHeight)
}
所以从原图的0,0位置取得与canvas大小一样的部分显示在canvas中,所以出现了上图的结果。
不知道理解的对不对,希望大神们可以指点一二~