html代码:
<!DOCTYPE html>
<html>
<head>
<title>Scaling image</title>
<style>
body {
background: rgba(100, 145, 250, 0.3);
}
#scaleSlider {
vertical-align:10px;
width: 100px;
margin-left: 90px;
}
#canvas {
margin: 10px 20px 0px 20px;
border: thin solid #aaa;
cursor: crossshair;
}
#controls {
margin-left: 15px;
padding: 0;
}
#scaleOutput {
position:absolute;
width : 60px;
height: 30px;
margin-left: 10px;
vertical-align: center;
color: blue;
font: 18px Arial;
text-shadow : 2px 2px 4px rgba(100, 140, 250, 0.8);
}
</style>
</head>
<body>
<div id="controls">
<output id="scaleOutput"> 1.0</output>
<input id="scaleSlider" type="range" min="1" max="3.0" step="0.01" value="1.0" />
</div>
<canvas id="canvas" width="800" height="520">
canvas not supported
</canvas>
<script src="drawimage2.js"></script>
</body>
</html>
js逻辑部分:
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
image = new Image(),
scaleSlider = document.getElementById('scaleSlider'),
scale = 1.0,
MININUM_SCALE = 1.0,
MAXINUM_SCALE = 3.0;
// function.......
function drawImage() {
var w = canvas.width,
h = canvas.height,
sw = w * scale,
sh = h * scale;
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(image, -sw/2 + w/2, -sh/2 + h/2, sw, sh);
}
function drawScaleText(value) {
var text = parseFloat(value).toFixed(2);
var percent = parseFloat(value - MININUM_SCALE)/
parseFloat(MAXINUM_SCALE - MININUM_SCALE);
scaleOutput.innerText = text;
percent = percent < 0.35 ? 0.35 : percent;
scaleOutput.style.fontSize = percent*MAXINUM_SCALE/1.5 + 'em';
}
// event handler
scaleSlider.onchange = function(e) {
scale = e.target.value;
if(scale < MININUM_SCALE) scale = MININUM_SCALE;
else if(scale > MAXINUM_SCALE) scale = MAXINUM_SCALE;
drawScaleText(scale);
drawImage();
}
// Initialization..................
context.fillstyle = 'cornflowerblue';
context.strokeStyle = 'yellow';
context.shadowColor = 'rgba(50,50,50,1.0)';
context.shadowOffsetX = 5;
context.shadowOffsetY = 5;
context.shadowBlur = 10;
image.src = 'timg.1.jpeg';
image.onload = function(e) {
drawImage();
drawScaleText(scaleSlider.value);
}