Calicol Calicol - 22 days ago 11
Javascript Question

How can I make this with Javascript or JQuery

How can I make this using javascript or jquery?
Example

The thing i want to do is create a figure (triangle) and make a tile with this figure like the one in the image with random colors

I have tried this



<html><head>
<style>
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
</style>
</head>
<body>
<canvas id="canvas" width="1000" height="1000"></canvas>
<script type="text/javascript">

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");

var cw=canvas.width;
var ch=canvas.height;

var colwidth=cw/20;
var rowheight=ch/20;

for(var y=0;y<20;y++){

for(var x=0;x<20;x++){

ctx.fillStyle=randomColor();
ctx.fillRect(x*colwidth,y*rowheight,colwidth,rowheight);
ctx.strokeRect(x*colwidth,y*rowheight,colwidth,rowheight);
}}

function randomColor(){
return('#'+Math.floor(Math.random()*12345678).toString(16));
}
</script>

</body></html>




Answer

You can easily do it with html/css only, depends how much browser support you need.

HTML

<div class="square"> <div class="triangle-left"></div> <div class="triangle-right"></div> </div>

CSS

.triangle-right{ position:absolute; bottom: 0; right: 0; width: 0; height: 0; border-left: 100px solid transparent; border-right: 0 solid transparent; border-bottom: 100px solid red; } .triangle-left{ position:absolute; top: 0; left: 0; width: 0; height: 0; border-right: 100px solid transparent; border-left: 0 solid transparent; border-top: 100px solid green; } .square{ position:relative; float: left; width: 100px; height: 100px; }

Comments