<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>drawImage</title>
<style>
body{
background:black;
}
canvas{
margin:20px auto;
border:1px solid #aaa;
display:block;
}
input{
display:block;
margin:20px auto;
width:800px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<input id="scale-range" type="range" min="0.5" max="3.0" step="0.01" value="3.0">
<script>
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var image = new Image();
var slider = document.getElementById("scale-range");
window.onload = function () {
canvas.width = 245;
canvas.height = 200;
var scale = slider.value;
// console.log(document.documentElement.clientHeight+"\n"+
// alert(document.documentElement.clientHeight);
image.src = "img/8.jpg";
image.onload = function () {
// context.drawImage(image,0,0);
// context.drawImage(image,0,0,canvas.width,canvas.height);
drawImageByScale(scale);
}
function drawImageByScale(sclae){
var imageWidth = 245*scale;
var imageHeight = 200*scale;
var sx = imageWidth/2 - canvas.width/2;
var sy = imageHeight/2 - canvas.height/2;
context.drawImage(image,sx,sy,canvas.width,canvas.height,0,0,canvas.width,canvas.height);
}
}
</script>
</body>
</html>
好的,谢谢。
如果你图片的原始尺寸是245*200
var sx = imageWidth/2 - canvas.width/2; var sy = imageHeight/2 - canvas.height/2;
计算出的sx和sy都超出了图片本身,不会绘制到画布上的
你看一下8.jpg图片宽度和高度,还有sx和sy计算得到的值,如果图片的值小于sx和sy的值是不会显示的