A
A
alto20132016-04-27 15:07:53
JavaScript
alto2013, 2016-04-27 15:07:53

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

5 answer(s)
Z
ZaptoS, 2016-04-27
@alto2013

<!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>

_
_ _, 2016-04-27
@AMar4enko

Well, it still needs to be done append

D
Dmitry Kiselev, 2016-04-27
@woland_812

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 number
ctx.fillRect(110, 110, parseInt(c1.style.width), parseInt(c1.style.height))

G
GreatRash, 2016-04-27
@GreatRash

Thirdly:

// c1.style.height = "400px";
// c1.style.width = "400px";

с1.width = 400;
c1.height = 400;

Otherwise, the canvas will stupidly scale.

D
Dmitry Belyaev, 2016-04-27
@bingo347

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 question

Ask a Question

731 491 924 answers to any question