当我添加
ctx.addEventListener('mousedown', onDown, false);
画布绘图(背景和形状)消失,页面为空白,然后当我从代码中删除此事件侦听器时,它们再次出现。只是想知道为什么会这样?提前致谢
<script>
var ctx, W, H;
var x = 10;
window.onload = function() {
var canvas = document.getElementById("canvas");
W = window.innerWidth;
H = window.innerHeight;
canvas.width = W;
canvas.height = H;
ctx = canvas.getContext("2d");
ctx.addEventListener('mousedown', onDown, false); //When this is here, canvas drawing disappears, when it's not here canvas drawing reappears again
setInterval(draw, 1);
function draw() {
ctx.globalCompositeOperation = "source-over";
ctx.fillStyle = "#E6E6FF";
ctx.fillRect(0, 0, W, H);
ctx.fillStyle = "black";
ctx.fillRect(x,20,10,10);
ctx.font = "30px Arial";
ctx.fillText("Hello World",10,80);
ctx.fill();
}
}
function onDown(event) {
//where x is found
cx = event.pageX
cy = event.pageY
alert("X,Y ="+cx+','+cy);
}
答案 0 :(得分:1)
您无法向画布的上下文添加事件侦听器。您需要将它添加到画布本身。
而不是:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import re
def drop_md5hash_varchar_pattern_ops_index(apps, schemaEditor):
# code based on https://docs.djangoproject.com/en/1.8/_modules/django/db/backends/base/schema/#BaseDatabaseSchemaEditor.alter_field
model = apps.get_model("logger", "Btilog")
index_names = schemaEditor._constraint_names(model, index=True)
for index_name in index_names:
if re.search('logger_btilog_md5hash_.+_like', index_name):
print 'dropping index {}'.format(index_name)
schemaEditor.execute(schemaEditor._delete_constraint_sql(schemaEditor.sql_delete_index, model, index_name))
class Migration(migrations.Migration):
dependencies = [
('logger', '0012_auto_20150529_1745'),
]
operations = [
# Remove the annoying index using a hack
migrations.RunPython(
drop_md5hash_varchar_pattern_ops_index
),
]
......这样做:
ctx.addEventListener('mousedown', onDown, false);
答案 1 :(得分:1)
<强> jsBin demo 强>
使用:
canvas.addEventListener('mousedown', onDown, false);
或:
ctx.canvas.addEventListener
因为canvas.addEventListener
只是HTMLElementCanvas所在的对象。
要发现自己的错误,最简单的方法是使用开发者工具调试代码,打开控制台选项卡并阅读显示的错误: