canvas-図形描画-画像描画(demoをスケール)
2734 ワード
htmlコード:
js セクション:
Scaling image
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);
}