我正在尝试在画布上绘制一个圆圈以匹配div的尺寸。我无法理解这里的错误(除了坏的风格),因为结果是省略号,看起来画布大小在绘图后被拉伸(JSFiddle here):
$(document).ready(function() {
scrH = $(window).height();
scrW = $(window).width();
// place map
$('body').append("<div id='pagUserStart_map1' style='border:5px solid red;'></div>");
var map = $("#pagUserStart_map1");
map.css("width", scrW - 60 + "px");
map.css("height", map.css("width"));
map.css("top", scrH / 2 - map.height()/2);
map.css("left", (scrW - map.width()) / 2);
map.css("position", "absolute");
map.css("margin", "0 auto");
map.css("border-radius", "50%");
map.css("z-index", "100");
//place canvas
$('body').append("<canvas id='canvas1'></canvas>");
var canvas = $("#canvas1");
canvas.width(map.width());
canvas.height(canvas.width());
canvas.css("position", "absolute");
canvas.position({
my: "center",
at: "center",
of: map
});
canvas = document.getElementById("canvas1");
// draw circle in canvas
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height /2 ;
var radius = 50;
context.beginPath();
context.arc(centerX, centerY, 50, 0, 2 * Math.PI, false);
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
context.shadowBlur = 10;
context.shadowColor = '#656565';
context.lineWidth = 10;
context.strokeStyle = '#B8CADE';
context.stroke();
});
我理解当我使用JQuery引用'canvas1'和使用getElementById时出现问题。但为什么?似乎代码不是按顺序执行的。我已经迷失了几个小时在谷歌上搜索代码...我真的需要你的帮助。
答案 0 :(得分:2)
您需要正确设置画布大小:
canvas.attr('width', map.width());
canvas.attr('height', map.height());
答案 1 :(得分:1)
设置画布元素宽度而不是画布css width:
// draw circle in canvas
canvas = document.getElementById("canvas1");
canvas.width=map.width();
canvas.height=map.height();
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height /2 ;
var radius = 50;
答案 2 :(得分:-1)
将absolute
位置简单地更改为fixed
。
像这样
$(document).ready(function(){
scrH = $(window).height();
scrW = $(window).width();
// place map
$('body').append("<div id='pagUserStart_map1' style='border:5px solid red;'></div>");
var map = $("#pagUserStart_map1");
map.css("width", scrW - 60 + "px");
map.css("height", map.css("width"));
map.css("top", scrH / 2 - map.height()/2);
map.css("left", (scrW - map.width()) / 2);
map.css("position", "fixed");
map.css("margin", "0 auto");
map.css("border-radius", "50%");
map.css("z-index", "100");
//place canvas
$('body').append("<canvas id='canvas1'></canvas>");
var canvas = $("#canvas1");
canvas.width(map.width());
canvas.height(canvas.width());
canvas.css("position", "fixed");
canvas.position({
my: "center",
at: "center",
of: map
});