【发布时间】:2015-02-19 21:38:37
【问题描述】:
当窗口调整大小事件触发时,我想在自定义 Polymer 元素上调整 html5 画布的大小!
我尝试使用 window.onresize 事件,但无法获取画布功能。
我们可以通过鼠标和触摸事件监听在这个 html5 画布上绘制东西! 我们使用聚合物和聚合物手势。
canvas {
background:url(BackgroundPattern.png);
}
@media (-webkit-min-device-pixel-ratio: 2),
(min-resolution: 192dpi) {
canvas {
background:url(BackgroundPattern@2x.png);
}
}
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../polymer-gestures/polymer-gestures.html">
<polymer-element name="mycustom-canvas">
<template>
<link rel="stylesheet" href="./mycustom-canvas.css">
<canvas id="canvas" touch-action="none"></canvas>
</template>
<script>
Polymer({
init: function (){
var canvas = this.$.canvas,
context = canvas.getContext('2d'),
windowWidth = window.innerWidth,
windowHeight = window.innerHeight,
scale = this.getPixelRatio();
canvas.width = windowWidth - canvas.offsetLeft;
canvas.height = windowHeight - canvas.offsetTop;
if (scale > 1) {
var newWidth = canvas.width * scale,
newHeight = canvas.height * scale;
canvas.style.width = canvas.width + 'px';
canvas.style.height = canvas.height + 'px';
canvas.width = newWidth;
canvas.height = newHeight;
context = canvas.getContext('2d');
}
context.lineWidth = 2 * scale;
context.lineCap = 'round';
context.lineJoin = 'round';
context.strokeStyle = 'rgb(0, 0, 0)';
},
getCoords: function (inEvent) {
var scale = this.getPixelRatio();
if (inEvent.offsetX) {
return { x: scale * inEvent.offsetX, y: scale * inEvent.offsetY };
}
else if (inEvent.layerX) {
return { x: scale * inEvent.layerX, y: scale * inEvent.layerY };
}
else {
return { x: scale * (inEvent.pageX - inEvent.target.offsetLeft), y: scale * (inEvent.pageY - inEvent.target.offsetTop) };
}
},
getPixelRatio: function () {
if ('devicePixelRatio' in window) {
if (window.devicePixelRatio > 1) {
return window.devicePixelRatio;
}
}
return 1;
},
ready: function () {
var events = [
// base events
'down',
'up',
'trackstart',
'track',
'trackend',
'tap',
'hold',
'holdpulse',
'release'
];
this.init();
events.forEach(function(en) {
PolymerGestures.addEventListener(this, en, function (inEvent) {
var coords = this.getCoords(inEvent);
switch (en) {
case 'down':
this.fire('mycustom-canvas-down', {event: inEvent, x : coords.x, y : coords.y});
break;
case 'track':
this.fire('mycustom-canvas-track', {event: inEvent, x : coords.x, y : coords.y});
break;
case 'up':
this.fire('mycustom-canvas-up', {event: inEvent, x : coords.x, y : coords.y});
break;
}
inEvent.preventDefault();
});
}, this);
}
});
</script>
</polymer-element>
现在我使用 window.height 和 window.width 作为画布初始尺寸,但我的最终目的是使用父容器尺寸。
【问题讨论】:
-
Polymer 团队构建了一个名为
<core-resizable>元素的非 UI 组件,它会触发core-resize事件,您可以利用该事件来调整画布大小。
标签: javascript html canvas polymer