<body>
<canvas id="canvas"></canvas>
<input id="range" type="range" step="0.01" min="0.5" max="3" value="2" />
<script>
window.onload = function(){
var canvas = document.getElementById('canvas');
var slide = document.getElementById('range');
var ctx = canvas.getContext('2d');
canvas.width = 400;
canvas.height = 252;
var scale = slide.value;
var img = new Image();
img.src = 'img/img3.jpg';
img.onload = function(){
drawImgByScale(scale);
};
function drawImgByScale(scale){
var iWidth = 400*scale;
var iHeight = 252*scale;
var sx = iWidth/2 - canvas.width/2;
var sy = iHeight/2 - canvas.height/2;
ctx.drawImage(img,sx,sy,canvas.width,canvas.height,0,0,canvas.width,canvas.height);
}
}
</script>
</body>
老师的的算法有问题,之所以他这个能实现,我想是图片分辨率足够大,换一个分辨率小的就不行了你可以用这个试试
function drawImageByScale(){
var imgW = cwidth/scale;
var imgH = cheight/scale;
var sx = cwidth/2-imgW/2;
var sy = cheight/2-imgH/2;
cxt.drawImage(bgimg,sx,sy,cwidth/scale,cheight/scale,0,0,cwidth,cheight);
}
可能是你用的老师之前的那张照片吧 清晰度比较低 不能再放大了 你换一张清晰度高点的就可以了
<script>
window.onload=function(){
var canvas=document.getElementById('canvas');
var context=canvas.getContext('2d');
var image=new Image();
var ran=document.getElementById('scale-range');
canvas.width=1152;
canvas.height=768;
image.src="img.jpg";
image.onload=function(){
//context.drawImage(image,0,0)
var slider=ran.value;
drawImageScale(slider)
}
function drawImageScale(slider){
var imgWidth=1152*slider;
var imgHeight=768*slider;
var sx=imgWidth / 2-canvas.width / 2;
var sy=imgHeight / 2-canvas.height / 2;
context.drawImage( image , sx , sy , canvas.width , canvas.height , 0 , 0 ,canvas.width , canvas.height)
}
}
</script>
<body>
<canvas id="canvas" style="border:#000 1px solid;display:block;margin:0 auto;">您浏览器版本太低</canvas>
<input type="range" id="scale-range" style="display:block;width:800px;margin:20px auto;" min="0.5" max="3.0" step="0.01" value="2.0"/>
</body>
为啥不能占满整个屏幕呢?
<body>
<canvas id="canvas"></canvas>
<input id="range" type="range" step="0.01" min="0.5" max="3" value="2" />
<script>
window.onload = function(){
var canvas = document.getElementById('canvas');
var slide = document.getElementById('range');
var ctx = canvas.getContext('2d');
canvas.width = 400;
canvas.height = 252;
var img = new Image();
img.src = '1.jpg';
img.onload = function(){
drawImgByScale(scale);}
slide.onmousemove = function(){
drawImgByScale(slide.value);
};
function drawImgByScale(scale){
var iWidth = 400*scale;
var iHeight = 252*scale;
var sx = iWidth/2 - canvas.width/2;
var sy = iHeight/2 - canvas.height/2;
ctx.drawImage(img,sx,sy,canvas.width,canvas.height,0,0,canvas.width,canvas.height);
}
}
</script>
</body>
代码改成这样会跟着滚动条动
drawImage(img,sx,sy,swidth,sheight,x,y,width,height);
img是需要绘制的图片,sx,xy是需要绘制的图片上的起点,而不是在canvas画布上的起点
swidth,sheight,是需要绘制图片的宽度和高度
x,y指的是要把绘制的图片放在画布的什么位置
width和height 图片总的大小