Answer the question
In order to leave comments, you need to log in
Is it possible to create a programmatically working canvas element in an html document?
почему не отрабатывает код?
<!doctype html><html> <head> <script type="text/javascript">
var c1 = document.createElement('canvas'); c1.style.height = "400px";
c1.style.width = "400px"; ctx = c1.getContext('2d');
ctx.fillRect(110, 110, c1.style.width, c1.style.height);
</script> </head><body></body></html>
Answer the question
In order to leave comments, you need to log in
<!doctype html>
<html>
<head>
<title>canvasExample</title>
</head>
<body>
<script type="text/javascript">
var c1 = document.createElement('canvas');
document.body.appendChild(c1);
c1.style.height = "400px";
c1.style.width = "400px";
ctx = c1.getContext('2d');
ctx.fillRect(110, 110, parseInt(c1.style.width), parseInt(c1.style.height));
</script>
</body>
</html>
Firstly, the element was created, but not added to the document
Secondly,
ctx.fillRect(110, 110, c1.style.width, c1.style.height)
it won't draw anything, because c1.style.width and c1.style.height will return the string "400px". Bring to numberctx.fillRect(110, 110, parseInt(c1.style.width), parseInt(c1.style.height))
Thirdly:
// c1.style.height = "400px";
// c1.style.width = "400px";
с1.width = 400;
c1.height = 400;
Fourth, do not use c1.style.height and c1.style.width in calculations, they can be in any units, use c1.offsetHeight and c1.offsetWidth - they will always be a number and in pixels
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question