Best JavaScript code snippet using playwright-internal
filterHotelsRooms.js
Source:filterHotelsRooms.js
1import React, { useCallback, useState, useEffect, memo } from 'react'2import { StyleSheet, View, Text, TouchableOpacity, Modal, Dimensions } from 'react-native'3import { Icon } from 'react-native-eva-icons';4import { useTranslation } from 'react-i18next';5import { colorAlfa, colorBetta, colorDelta, colorDseta, colorEpsilon, colorKappa, colorZeta } from '../../styles/Colors';6import Toast from 'react-native-simple-toast';7import { ScrollView, TextInput } from 'react-native-gesture-handler';8import Slider from 'rn-range-slider';9//import RangeSlider from 'rn-range-slider';10function FilterHotelsRooms(props) {11 const { t, i18n } = useTranslation();12 const windowWidth = Dimensions.get('window').width;13 const windowHeight = Dimensions.get('window').height;14 const [mega, setmega] = useState(false);15 const [pop, setpop] = useState(false);16 const [persons, setpersons] = useState(false);17 const [kids, setkids] = useState(0);18 const [adults, setadults] = useState(1);19 const [bedrooms, setbedrooms] = useState(1);20 function getkids(v) {21 let value = v + kids22 if (value < 0) {23 setkids(0)24 }25 else {26 setkids(value)27 }28 }29 function getadults(v) {30 let value = v + adults31 if (value <= 0) {32 setadults(1)33 }34 else {35 setadults(value)36 }37 }38 function getbedrooms(v) {39 let value = v + bedrooms40 if (value <= 0) {41 setbedrooms(1)42 }43 else {44 setbedrooms(value)45 }46 }47 function getpersons() {48 send()49 setpop(false)50 setpersons(false)51 }52 function resetpersons() {53 setkids(0);54 setadults(1);55 setbedrooms(1);56 }57 /* _____________________________________________________________ */58 const [category, setcategory] = useState(false);59 const [categoryValue, setcategoryValue] = useState(0);60 function getCategory() {61 send()62 setpop(false)63 setcategory(false)64 }65 /* _____________________________________________________________ */66 const [preferences, setpreferences] = useState(false);67 const [preferencesList, setpreferencesList] = useState([68 { id: 12, icon: "star", name: "spa", checked: false },69 { id: 9, icon: "wifi-outline", name: "wi-fi", checked: false },70 { id: 2, icon: "star", name: "piscina", checked: false },71 { id: 5, icon: "people-outline", name: "familias", checked: false },72 { id: 7, icon: "star", name: "gimnasio", checked: false },73 { id: 3, icon: "star", name: "parqueadero", checked: true },74 { id: 4, icon: "star", name: "restaurante", checked: true },75 { id: 8, icon: "star", name: "deesayuno gratis", checked: false },76 { id: 14, icon: "pricetags-outline", name: "oferta ingreÃble", checked: false },77 { id: 9, icon: "star", name: "aire-acondicionado", checked: false },78 { id: 10, icon: "star", name: "mascotas permitidas", checked: false },79 { id: 1, icon: "gift-outline", name: "cancelación gratuita", checked: false },80 { id: 6, icon: "star", name: "bañera de hidromasaja", checked: false },81 { id: 11, icon: "credit-card-outline", name: "pago en el alojamiento", checked: false },82 { id: 13, icon: "star", name: "acceso silla de ruedas", checked: false },83 ]);84 function checkPreference(text) {85 let state, value86 for (var i in preferencesList) {87 if (preferencesList[i].name === text) {88 state = preferencesList[i].checked89 }90 }91 value = !state92 // preferencesList[i].checked:value93 // setpreferencesList({94 // ...preferencesList,95 // [text.checked]: value96 // })97 }98 function getPreferences() {99 send()100 setpop(false)101 setpreferences(false);102 }103 /* _____________________________________________________________ */104 // const [priceMin, setpriceMin] = useState(false);105 // const [priceMax, setpriceMin] = useState(false);106 // const renderThumb = useCallback(() => <Thumb />, []);107 // const renderRail = useCallback(() => <Rail />, []);108 // const renderRailSelected = useCallback(() => <RailSelected />, []);109 // const renderLabel = useCallback(value => <Label text={value} />, []);110 // const renderNotch = useCallback(() => <Notch />, []);111 const renderThumb = useCallback(() => Thumb(), []);112 const renderRail = useCallback(() => Rail(), []);113 const renderRailSelected = useCallback(() => RailSelected(), []);114 const renderLabel = useCallback(value => Label(value), []);115 const renderNotch = useCallback(() => Notch(), []);116 const handleValueChange = useCallback((low, high) => {117 console.log("min", low)118 console.log("max", high)119 }, []);120 // const [rangeDisabled, setRangeDisabled] = useState(false);121 // const [low, setLow] = useState(0);122 // const [high, setHigh] = useState(100);123 // const [min, setMin] = useState(0);124 // const [max, setMax] = useState(100);125 // const [floatingLabel, setFloatingLabel] = useState(false);126 // const renderThumb = useCallback(() => <Thumb />, []);127 // const renderRail = useCallback(() => <Rail />, []);128 // const renderRailSelected = useCallback(() => <RailSelected />, []);129 // const renderLabel = useCallback(value => <Label text={value} />, []);130 // const renderNotch = useCallback(() => <Notch />, []);131 // const handleValueChange = useCallback((low, high) => {132 // setLow(low);133 // setHigh(high);134 // }, []);135 // const toggleRangeEnabled = useCallback(() => setRangeDisabled(!rangeDisabled), [rangeDisabled]);136 // const setMinTo50 = useCallback(() => setMin(50), []);137 // const setMinTo0 = useCallback(() => setMin(0), []);138 // const setMaxTo100 = useCallback(() => setMax(100), []);139 // const setMaxTo500 = useCallback(() => setMax(500), []);140 // const toggleFloatingLabel = useCallback(() => setFloatingLabel(!floatingLabel), [floatingLabel]);141 /* _____________________________________________________________ */142 // const [dataInit, setdataInit] = useState("");143 // const [dateEnd, setdateEnd] = useState("");144 /* _____________________________________________________________ */145 // const [search, setsearch] = useState("");146 /* _____________________________________________________________ */147 function send() {148 console.log("send ....")149 }150 const iconColor = "silver"151 return (152 <View style={styles.filterWrap}>153 {mega === false &&154 <TouchableOpacity onPress={() => setmega(!mega)}155 style={{ position: "absolute", top: 0, right: 0, backgroundColor: colorZeta, padding: 10, zIndex: 9999, borderBottomLeftRadius: 20 }}>156 <Icon name={'settings-outline'} fill={iconColor} width={25} height={25} />157 </TouchableOpacity>158 }159 {mega === true &&160 <>161 <View style={styles.filterWrapRow}>162 <TouchableOpacity style={styles.filterBtn} onPress={() => [setpersons(true), setpop(true)]}>163 <Icon name={'people-outline'} fill={iconColor} width={25} height={25} />164 <Text style={styles.filterBtnText}>persons: {kids + adults}</Text>165 </TouchableOpacity>166 <TouchableOpacity style={styles.filterBtn} onPress={() => [setcategory(true), setpop(true)]}>167 <Icon name={'star'} fill={iconColor} width={25} height={25} />168 <Text style={styles.filterBtnText}>category: {categoryValue}</Text>169 </TouchableOpacity>170 <TouchableOpacity style={styles.filterBtn} onPress={() => [setpreferences(true), setpop(true)]}>171 <Icon name={'settings-outline'} fill={iconColor} width={25} height={25} />172 <Text style={styles.filterBtnText}>preferencias</Text>173 </TouchableOpacity>174 </View>175 <View style={styles.filterWrapRow}>176 <Icon name={'calendar'} fill={iconColor} width={30} height={30} />177 <TouchableOpacity style={styles.filterBtn}>178 <Text style={[styles.filterBtnText, { fontWeight: "bold" }]}>llegada: </Text><Text style={styles.filterBtnText}>vi, 00/00/00</Text>179 </TouchableOpacity>180 <TouchableOpacity style={styles.filterBtn}>181 <Text style={[styles.filterBtnText, { fontWeight: "bold" }]}>salida: </Text><Text style={styles.filterBtnText}>do, 00/00/00</Text>182 </TouchableOpacity>183 </View>184 <View style={styles.filterWrapRow}>185 <View style={{ flexDirection: "column" }}>186 <View style={{ flexDirection: "row" }}>187 <Icon name={'credit-card-outline'} fill={iconColor} width={30} height={30} />188 <TouchableOpacity style={[styles.filterBtn, { minWidth: "43%" }]}>189 <Text style={[styles.filterBtnText]}>234.000,88</Text>190 </TouchableOpacity>191 <TouchableOpacity style={[styles.filterBtn, { minWidth: "43%" }]}>192 <Text style={[styles.filterBtnText]}>634.000,88</Text>193 </TouchableOpacity>194 </View>195 <View style={{ flexDirection: "row" }}>196 <Slider197 style={{}}198 min={0}199 max={100}200 step={1}201 floatingLabel202 renderThumb={renderThumb}203 renderRail={renderRail}204 renderRailSelected={renderRailSelected}205 renderLabel={renderLabel}206 renderNotch={renderNotch}207 onValueChanged={handleValueChange}208 />209 </View>210 </View></View>211 <View style={styles.filterWrapRow}>212 <TextInput value={"rtyrtry"} />213 </View>214 </>215 }216 <Modal animationType="slide" transparent={true} visible={pop}>217 <View style={{ backgroundColor: colorKappa, flex: 1, justifyContent: "center", alignContent: "center", alignItems: "center" }}>218 {persons === true &&219 <View style={styles.windowPop}>220 <View style={styles.groupRowFootBtnHead}>221 <Text style={styles.groupRowFootBtnHeadTitle}>Persons & Rooms</Text>222 </View>223 <View style={styles.groupRow}>224 <Text style={styles.groupRowName}>niños</Text>225 <TouchableOpacity onPress={() => getkids(-1)} style={styles.groupRowBtn}>226 <Icon name='minus-circle-outline' fill={colorEpsilon} width={30} height={30} />227 </TouchableOpacity>228 <Text style={styles.groupRowValue}>{kids}</Text>229 <TouchableOpacity onPress={() => getkids(+1)} style={styles.groupRowBtn}>230 <Icon name='plus-circle-outline' fill={colorEpsilon} width={30} height={30} />231 </TouchableOpacity>232 </View>233 <View style={styles.groupRow}>234 <Text style={styles.groupRowName}>adultos</Text>235 <TouchableOpacity onPress={() => getadults(-1)} style={styles.groupRowBtn}>236 <Icon name='minus-circle-outline' fill={colorEpsilon} width={30} height={30} />237 </TouchableOpacity>238 <Text style={styles.groupRowValue}>{adults}</Text>239 <TouchableOpacity onPress={() => getadults(+1)} style={styles.groupRowBtn}>240 <Icon name='plus-circle-outline' fill={colorEpsilon} width={30} height={30} />241 </TouchableOpacity>242 </View>243 <View style={styles.groupRow}>244 <Text style={styles.groupRowName}>rooms</Text>245 <TouchableOpacity onPress={() => getbedrooms(-1)} style={styles.groupRowBtn}>246 <Icon name='minus-circle-outline' fill={colorEpsilon} width={30} height={30} />247 </TouchableOpacity>248 <Text style={styles.groupRowValue}>{bedrooms}</Text>249 <TouchableOpacity onPress={() => getbedrooms(+1)} style={styles.groupRowBtn}>250 <Icon name='plus-circle-outline' fill={colorEpsilon} width={30} height={30} />251 </TouchableOpacity>252 </View>253 <View style={styles.groupRowFoot}>254 <TouchableOpacity onPress={() => resetpersons()} style={[styles.groupRowFootBtn, styles.btnOFF]}>255 <Text style={[styles.groupRowFootBtnText, { color: "#777" }]}>reset</Text>256 </TouchableOpacity>257 <TouchableOpacity onPress={() => getpersons()} style={[styles.groupRowFootBtn, styles.btnON]}>258 <Text style={[styles.groupRowFootBtnText, { color: colorAlfa }]}>aceptar</Text>259 </TouchableOpacity>260 </View>261 </View>}262 {category === true &&263 <View style={styles.windowPop}>264 <View style={styles.groupRowFootBtnHead}>265 <Text style={styles.groupRowFootBtnHeadTitle}>Category</Text>266 </View>267 <View style={{ alignItems: "center" }}>268 <TouchableOpacity onPress={() => setcategoryValue(0)} style={{ flexDirection: "row", paddingVertical: 5, borderBottomColor: "silver", borderBottomWidth: 0.5 }}>269 <Icon name='star-outline' fill={colorDelta} width={30} height={30} />270 <Icon name='star-outline' fill={colorDelta} width={30} height={30} />271 <Icon name='star-outline' fill={colorDelta} width={30} height={30} />272 <Icon name='star-outline' fill={colorDelta} width={30} height={30} />273 <Icon name='star-outline' fill={colorDelta} width={30} height={30} />274 <Icon name={categoryValue === 0 ? 'checkmark-square-2-outline' : 'square-outline'} fill={categoryValue === 0 ? colorBetta : colorEpsilon} width={30} height={30} style={{ marginLeft: 20 }} />275 </TouchableOpacity>276 <TouchableOpacity onPress={() => setcategoryValue(1)} style={{ flexDirection: "row", paddingVertical: 5, borderBottomColor: "silver", borderBottomWidth: 0.5 }}>277 <Icon name='star' fill={colorDelta} width={30} height={30} />278 <Icon name='star-outline' fill={colorDelta} width={30} height={30} />279 <Icon name='star-outline' fill={colorDelta} width={30} height={30} />280 <Icon name='star-outline' fill={colorDelta} width={30} height={30} />281 <Icon name='star-outline' fill={colorDelta} width={30} height={30} />282 <Icon name={categoryValue === 1 ? 'checkmark-square-2-outline' : 'square-outline'} fill={categoryValue === 1 ? colorBetta : colorEpsilon} width={30} height={30} style={{ marginLeft: 20 }} />283 </TouchableOpacity>284 <TouchableOpacity onPress={() => setcategoryValue(2)} style={{ flexDirection: "row", paddingVertical: 5, borderBottomColor: "silver", borderBottomWidth: 0.5 }}>285 <Icon name='star' fill={colorDelta} width={30} height={30} />286 <Icon name='star' fill={colorDelta} width={30} height={30} />287 <Icon name='star-outline' fill={colorDelta} width={30} height={30} />288 <Icon name='star-outline' fill={colorDelta} width={30} height={30} />289 <Icon name='star-outline' fill={colorDelta} width={30} height={30} />290 <Icon name={categoryValue === 2 ? 'checkmark-square-2-outline' : 'square-outline'} fill={categoryValue === 2 ? colorBetta : colorEpsilon} width={30} height={30} style={{ marginLeft: 20 }} />291 </TouchableOpacity>292 <TouchableOpacity onPress={() => setcategoryValue(3)} style={{ flexDirection: "row", paddingVertical: 5, borderBottomColor: "silver", borderBottomWidth: 0.5 }}>293 <Icon name='star' fill={colorDelta} width={30} height={30} />294 <Icon name='star' fill={colorDelta} width={30} height={30} />295 <Icon name='star' fill={colorDelta} width={30} height={30} />296 <Icon name='star-outline' fill={colorDelta} width={30} height={30} />297 <Icon name='star-outline' fill={colorDelta} width={30} height={30} />298 <Icon name={categoryValue === 3 ? 'checkmark-square-2-outline' : 'square-outline'} fill={categoryValue === 3 ? colorBetta : colorEpsilon} width={30} height={30} style={{ marginLeft: 20 }} />299 </TouchableOpacity>300 <TouchableOpacity onPress={() => setcategoryValue(4)} style={{ flexDirection: "row", paddingVertical: 5, borderBottomColor: "silver", borderBottomWidth: 0.5 }}>301 <Icon name='star' fill={colorDelta} width={30} height={30} />302 <Icon name='star' fill={colorDelta} width={30} height={30} />303 <Icon name='star' fill={colorDelta} width={30} height={30} />304 <Icon name='star' fill={colorDelta} width={30} height={30} />305 <Icon name='star-outline' fill={colorDelta} width={30} height={30} />306 <Icon name={categoryValue === 4 ? 'checkmark-square-2-outline' : 'square-outline'} fill={categoryValue === 4 ? colorBetta : colorEpsilon} width={30} height={30} style={{ marginLeft: 20 }} />307 </TouchableOpacity>308 <TouchableOpacity onPress={() => setcategoryValue(5)} style={{ flexDirection: "row", paddingVertical: 5, borderBottomColor: "silver", borderBottomWidth: 0.5 }}>309 <Icon name='star' fill={colorDelta} width={30} height={30} />310 <Icon name='star' fill={colorDelta} width={30} height={30} />311 <Icon name='star' fill={colorDelta} width={30} height={30} />312 <Icon name='star' fill={colorDelta} width={30} height={30} />313 <Icon name='star' fill={colorDelta} width={30} height={30} />314 <Icon name={categoryValue === 5 ? 'checkmark-square-2-outline' : 'square-outline'} fill={categoryValue === 5 ? colorBetta : colorEpsilon} width={30} height={30} style={{ marginLeft: 20 }} />315 </TouchableOpacity>316 </View>317 <View style={styles.groupRowFoot}>318 <TouchableOpacity onPress={() => getCategory()} style={[styles.groupRowFootBtn, styles.btnON]}>319 <Text style={[styles.groupRowFootBtnText, { color: colorAlfa }]}>aceptar</Text>320 </TouchableOpacity>321 </View>322 </View>}323 {preferences === true &&324 <View style={styles.windowPop}>325 <View style={styles.groupRowFootBtnHead}>326 <Text style={styles.groupRowFootBtnHeadTitle}>Preferences</Text>327 </View>328 <View style={{ height: windowHeight - 300 }}>329 <ScrollView>330 <View style={{331 width: "100%",332 paddingHorizontal: 10,333 width: "100%",334 alignItems: "center",335 alignContent: "center",336 justifyContent: "center",337 }}>338 {339 preferencesList.map((i, key) => {340 return (341 <TouchableOpacity key={key}342 style={{343 margin: 2,344 paddingVertical: 5,345 paddingHorizontal: 15,346 width: "80%",347 backgroundColor: colorZeta,348 justifyContent: "space-between",349 borderRadius: 12,350 flexDirection: "row",351 borderWidth: 0.5,352 borderColor: colorEpsilon353 }}354 onPress={() => checkPreference(i.name)}355 >356 <Icon name={i.icon} fill={colorEpsilon} width={30} height={30} />357 <Text style={{ marginLeft: 5 }}>{i.name}</Text>358 <Icon name={i.checked === true ? 'checkmark-square-2-outline' : 'square-outline'} fill={i.checked === true ? colorBetta : colorEpsilon} width={30} height={30} />359 </TouchableOpacity>360 )361 })362 }363 </View>364 </ScrollView>365 </View>366 <View style={styles.groupRowFoot}>367 <TouchableOpacity onPress={() => getPreferences()} style={[styles.groupRowFootBtn, styles.btnON]}>368 <Text style={[styles.groupRowFootBtnText, { color: colorAlfa }]}>aceptar</Text>369 </TouchableOpacity>370 </View>371 </View>372 }373 </View>374 </Modal>375 </View>376 )377}378function Thumb() {379 const THUMB_RADIUS = 12;380 return (<View style={{381 width: THUMB_RADIUS * 2,382 height: THUMB_RADIUS * 2,383 borderRadius: THUMB_RADIUS,384 borderWidth: 2,385 borderColor: '#7f7f7f',386 backgroundColor: '#ffffff',387 }} />)388}389function Label({ text, ...restProps }) {390 return (391 <View style={{392 alignItems: 'center',393 padding: 8,394 backgroundColor: '#4499ff',395 borderRadius: 4,396 }} {...restProps}>397 <Text style={{398 fontSize: 16,399 color: '#fff',400 }}>{text}</Text>401 </View>402 )403}404function Rail() {405 return (<View style={{406 flex: 1,407 height: 4,408 borderRadius: 2,409 backgroundColor: '#7f7f7f',410 }} />)411}412function RailSelected() {413 return (<View style={{414 height: 4,415 backgroundColor: '#4499ff',416 borderRadius: 2,417 }} />)418}419function Notch(props) {420 return (421 <View style={{422 width: 8,423 height: 8,424 borderLeftColor: 'transparent',425 borderRightColor: 'transparent',426 borderTopColor: '#4499ff',427 borderLeftWidth: 4,428 borderRightWidth: 4,429 borderTopWidth: 8,430 }} {...props} />431 )432}433const styles = StyleSheet.create({434 filterWrap: {435 marginBottom: 30,436 flexDirection: "column"437 },438 filterWrapRow: {439 borderBottomColor: "silver",440 borderBottomWidth: 0.5,441 paddingVertical: 8,442 paddingHorizontal: 10,443 flexDirection: "row",444 justifyContent: "space-around"445 },446 filterBtn: {447 // borderWidth: 1,448 // borderColor: colorAlfa,449 paddingHorizontal: 10,450 borderRadius: 12,451 marginHorizontal: 2,452 backgroundColor: colorZeta,453 justifyContent: "center",454 alignContent: "center",455 alignItems: "center",456 flexDirection: "row"457 },458 filterBtnText: {459 lineHeight: 30,460 marginLeft: 5,461 color: "#000",462 fontSize: 14463 },464 filterBtnDate: {},465 filterBtnPrice: {},466 filterBtnInput: {},467 windowPop: {468 width: "90%",469 backgroundColor: colorZeta,470 overflow: "hidden",471 borderRadius: 12,472 paddingBottom: 20,473 flexDirection: "column",474 shadowColor: "#000",475 shadowOffset: {476 width: 0,477 height: 2,478 },479 shadowOpacity: 0.25,480 shadowRadius: 3.84,481 elevation: 5,482 },483 groupRowFootBtnHead: {484 backgroundColor: colorBetta,485 padding: 10,486 marginBottom: 10,487 },488 groupRowFootBtnHeadTitle: {489 textAlign: "center",490 color: colorZeta,491 fontSize: 18,492 fontWeight: "bold"493 },494 groupRow: {495 borderBottomColor: "#ededed",496 borderBottomWidth: 0.5,497 flexDirection: "row",498 paddingVertical: 5,499 justifyContent: "space-around",500 paddingHorizontal: 20501 },502 groupRowName: {503 width: "50%",504 lineHeight: 40,505 fontSize: 18,506 fontWeight: "bold"507 },508 groupRowValue: {509 height: 40,510 backgroundColor: "#ededed",511 width: 60,512 lineHeight: 40,513 textAlign: "center",514 fontWeight: "700",515 fontSize: 16,516 borderRadius: 8517 },518 groupRowBtn: {519 marginHorizontal: 5,520 backgroundColor: "white",521 width: 40,522 height: 40,523 borderRadius: 40,524 justifyContent: "center",525 alignItems: "center",526 alignContent: "center"527 },528 groupRowFoot: {529 paddingTop: 20,530 borderTopColor: "silver",531 borderTopWidth: 1,532 flexDirection: "row",533 justifyContent: "space-around"534 },535 groupRowFootBtn: {536 maxWidth: "45%",537 width: "40%",538 paddingVertical: 8,539 paddingHorizontal: 15,540 borderRadius: 12,541 },542 groupRowFootBtnText: {543 textAlign: "center",544 textTransform: "uppercase"545 },546 btnON: {547 borderColor: colorAlfa,548 borderWidth: 1,549 },550 btnOFF: {551 borderColor: "#777",552 borderWidth: 1,553 }554})...
mp1.js
Source:mp1.js
1/**2 * @file UIUC CS418 MP1 A Dancing Logo3 * @author Minghao Liu <ml58@illinois.edu>4 */5/** @global The WebGL context */6var gl;7/** @global The HTML5 canvas we draw on */8var canvas;9/** @global A simple GLSL shader program */10var shaderProgram;11//variables for the logo12/** @global The WebGL buffers holding the triangle for the logo*/13var vertexPositionBufferTop;14var vertexPositionBufferMid;15var vertexPositionBufferBot;16var vertexPositionBufferTopInner;17var vertexPositionBufferMidInner;18var vertexPositionBufferBotInner;19/** @global The WebGL buffers holding the vertex colors for the logo*/20var vertexBlueBufferTop;21var vertexBlueBufferMid;22var vertexBlueBufferBot;23var vertexOrangeBufferTop;24var vertexOrangeBufferMid;25var vertexOrangeBufferBot;26/** @global The Modelview matrix */27var mvMatrix = mat4.create();28/** @global The angle of rotation around the x axis */29var rotAngle = 0;30/** @global If the rotation is clockwise; this dictates the cycle*/31var clockwise = true;32/** @global The translation on x coodinate */33var transX = 0;34/** @global The translation on y coodinate */35var transY = 0;36/** @global The delta of the non-uniform transformation */37var delta = 0;38//variables for the custom animation39/** @global The buffer holding the vertex positions for the square */40var vertexPositionBufferCustom;41/** @global The buffer holding the colors for the square */42var vertexColorBufferCustom;43/** @global The color change variable, updated each tick */44var colorDelta = 0.0;45/** @global flag for custom animation to maintain a cycle*/46var flag = true;47/**48 * Radio button control49 * @return {Boolean} True if logo is selected; false if custom animation is selected50 */51function isLogo() {52 return document.getElementById("Logo").checked;53}54//GL setup for both animations55/**56 * Sends projection/modelview matrices to shader57 */58function setMatrixUniforms() {59 gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);60}61/**62 * Creates a context for WebGL63 * @param {element} canvas WebGL canvas64 * @return {Object} WebGL context65 */66function createGLContext(canvas) {67 var context = null;68 context = canvas.getContext("webgl");69 if (context) {70 context.viewportWidth = canvas.width;71 context.viewportHeight = canvas.height;72 } else {73 alert("Failed to create WebGL context!");74 }75 return context;76}77/**78 * Loads Shaders79 * @param {string} id ID string for shader to load. Either vertex shader/fragment shader80 */81function loadShaderFromDOM(id) {82 var shaderScript = document.getElementById(id);83 84 // If we don't find an element with the specified id85 // we do an early exit 86 if (!shaderScript) {87 return null;88 }89 90 // Loop through the children for the found DOM element and91 // build up the shader source code as a string92 var shaderSource = "";93 var currentChild = shaderScript.firstChild;94 while (currentChild) {95 if (currentChild.nodeType == 3) { // 3 corresponds to TEXT_NODE96 shaderSource += currentChild.textContent;97 }98 currentChild = currentChild.nextSibling;99 }100 101 var shader;102 if (shaderScript.type == "x-shader/x-fragment") {103 shader = gl.createShader(gl.FRAGMENT_SHADER);104 } else if (shaderScript.type == "x-shader/x-vertex") {105 shader = gl.createShader(gl.VERTEX_SHADER);106 } else {107 return null;108 }109 110 gl.shaderSource(shader, shaderSource);111 gl.compileShader(shader);112 113 if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {114 alert(gl.getShaderInfoLog(shader));115 return null;116 } 117 return shader;118}119/**120 * Setup the fragment and vertex shaders121 */122function setupShaders() {123 vertexShader = loadShaderFromDOM("shader-vs");124 fragmentShader = loadShaderFromDOM("shader-fs");125 126 shaderProgram = gl.createProgram();127 gl.attachShader(shaderProgram, vertexShader);128 gl.attachShader(shaderProgram, fragmentShader);129 gl.linkProgram(shaderProgram);130 if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {131 alert("Failed to setup shaders");132 }133 gl.useProgram(shaderProgram);134 shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");135 shaderProgram.vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor"); 136 shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix");137}138//Setup, drawing and animation for the Logo Buffers139/**140 * Populate the Logo buffers with data141 */142function setUpBuffersLogo() {143 144 //We draw the logo in 6 parts, thus 6 buffers. We have 3 blue parts and 3 orange parts. The 3 buffers with the same color are combined to an "I"145 146 //Initialize Buffers147 vertexPositionBufferTop = gl.createBuffer();148 149 vertexBlueBufferTop = gl.createBuffer();150 151 vertexPositionBufferMid = gl.createBuffer();152 153 vertexBlueBufferMid = gl.createBuffer();154 155 vertexPositionBufferBot = gl.createBuffer();156 157 vertexBlueBufferBot = gl.createBuffer();158 159 vertexPositionBufferTopInner = gl.createBuffer();160 161 vertexOrangeBufferTop = gl.createBuffer();162 163 vertexPositionBufferMidInner = gl.createBuffer();164 165 vertexOrangeBufferMid = gl.createBuffer();166 167 vertexPositionBufferBotInner = gl.createBuffer();168 169 vertexOrangeBufferBot = gl.createBuffer();170 171 172 //draw outer part of the logo173 174 //top blue part175 var topVertices = [176 -1.0/3, 0.7/3, 0.0,177 -1.0/3, 1.5/3, 0.0,178 -0.55/3, 0.7/3, 0.0,179 1.0/3, 1.5/3, 0.0,180 1.0/3, 0.7/3, 0.0181 ];182 var topColors = [183 19.0/255.0, 41.0/255.0, 75.0/255.0, 1.0,184 19.0/255.0, 41.0/255.0, 75.0/255.0, 1.0,185 19.0/255.0, 41.0/255.0, 75.0/255.0, 1.0,186 19.0/255.0, 41.0/255.0, 75.0/255.0, 1.0,187 19.0/255.0, 41.0/255.0, 75.0/255.0, 1.0188 ];189 190 updateBuffer(vertexPositionBufferTop, topVertices, vertexBlueBufferTop, topColors);191 192 193 //middle blue part194 var midVertices = [195 -0.55/3, 0.7/3, 0.0,196 0.55/3, 0.7/3, 0.0,197 -0.55/3, -0.7/3, 0.0,198 0.55/3, -0.7/3, 0.0199 ];200 var midColors = [201 19.0/255.0, 41.0/255.0, 75.0/255.0, 1.0,202 19.0/255.0, 41.0/255.0, 75.0/255.0, 1.0,203 19.0/255.0, 41.0/255.0, 75.0/255.0, 1.0,204 19.0/255.0, 41.0/255.0, 75.0/255.0, 1.0205 ];206 updateBuffer(vertexPositionBufferMid, midVertices, vertexBlueBufferMid, midColors);207 208 //bottom blue part209 var botVertices = [210 -1.0/3, -0.7/3, 0.0,211 -1.0/3, -1.5/3, 0.0,212 -0.55/3, -0.7/3, 0.0,213 1.0/3, -1.5/3, 0.0,214 1.0/3, -0.7/3, 0.0215 ];216 var botColors = [217 19.0/255.0, 41.0/255.0, 75.0/255.0, 1.0,218 19.0/255.0, 41.0/255.0, 75.0/255.0, 1.0,219 19.0/255.0, 41.0/255.0, 75.0/255.0, 1.0,220 19.0/255.0, 41.0/255.0, 75.0/255.0, 1.0,221 19.0/255.0, 41.0/255.0, 75.0/255.0, 1.0,222 19.0/255.0, 41.0/255.0, 75.0/255.0, 1.0223 224 ];225 226 updateBuffer(vertexPositionBufferBot, botVertices, vertexBlueBufferBot, botColors);227 228 229 230 //The inner part of the logo231 232 //top orange part233 var topInnerVertices = [234 -0.9/3, 0.8/3, -0.1,235 -0.9/3, 1.4/3, -0.1,236 -0.55/3, 0.8/3, -0.1,237 0.9/3, 1.4/3, -0.1,238 0.9/3, 0.8/3, -0.1239 ]; 240 var topInnerColors = [241 232.0/255.0, 74.0/255.0, 39.0/255.0, 1.0,242 232.0/255.0, 74.0/255.0, 39.0/255.0, 1.0,243 232.0/255.0, 74.0/255.0, 39.0/255.0, 1.0,244 232.0/255.0, 74.0/255.0, 39.0/255.0, 1.0,245 232.0/255.0, 74.0/255.0, 39.0/255.0, 1.0246 247 ];248 249 updateBuffer(vertexPositionBufferTopInner, topInnerVertices, vertexOrangeBufferTop, topInnerColors);250 251 252 //middle orange part253 var midInnerVertices = [254 -0.45/3, 0.8/3, -0.1,255 0.45/3, 0.8/3, -0.1,256 -0.45/3, -0.8/3, -0.1,257 0.45/3, -0.8/3, -0.1258 ];259 var midInnerColors = [260 232.0/255.0, 74.0/255.0, 39.0/255.0, 1.0,261 232.0/255.0, 74.0/255.0, 39.0/255.0, 1.0,262 232.0/255.0, 74.0/255.0, 39.0/255.0, 1.0,263 232.0/255.0, 74.0/255.0, 39.0/255.0, 1.0264 ];265 266 updateBuffer(vertexPositionBufferMidInner, midInnerVertices, vertexOrangeBufferMid, midInnerColors);267 268 269 //bottom blue part270 var botInnerVertices = [271 -0.9/3, -0.8/3, -0.1,272 -0.9/3, -1.4/3, -0.1,273 -0.55/3, -0.8/3, -0.1,274 0.9/3, -1.4/3, -0.1,275 0.9/3, -0.8/3, -0.1276 ];277 var botInnerColors = [278 232.0/255.0, 74.0/255.0, 39.0/255.0, 1.0,279 232.0/255.0, 74.0/255.0, 39.0/255.0, 1.0,280 232.0/255.0, 74.0/255.0, 39.0/255.0, 1.0,281 232.0/255.0, 74.0/255.0, 39.0/255.0, 1.0,282 232.0/255.0, 74.0/255.0, 39.0/255.0, 1.0283 284 ];285 286 updateBuffer(vertexPositionBufferBotInner, botInnerVertices, vertexOrangeBufferBot, botInnerColors);287 288}289/**290 * draw call that applies matrix transformations to model and draws model in frame291 */292function drawLogo() { 293 gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);294 gl.clear(gl.COLOR_BUFFER_BIT);295 296 //Setup matrices for affine transformations297 mat4.fromTranslation(mvMatrix, vec3.fromValues(transX, transY, 0))298 mat4.rotateZ(mvMatrix, mvMatrix, degToRad(rotAngle)); 299 setMatrixUniforms();300 301 302 //set up new vertex positions for non-uniform transformation303 var updatedPosition = [304 (-1.0-delta)/3, -0.7/3, 0.0,305 (-1.0-delta)/3, -(1.5+delta)/3, 0.0,306 (-0.55-delta)/3, -0.7/3, 0.0,307 (1.0-delta)/3, -(1.5-delta)/3, 0.0,308 (1.0-delta)/3, -0.7/3, 0.0309 ];310 311 var blue = [312 19.0/255.0, 41.0/255.0, 75.0/255.0, 1.0,313 19.0/255.0, 41.0/255.0, 75.0/255.0, 1.0,314 19.0/255.0, 41.0/255.0, 75.0/255.0, 1.0,315 19.0/255.0, 41.0/255.0, 75.0/255.0, 1.0,316 19.0/255.0, 41.0/255.0, 75.0/255.0, 1.0,317 19.0/255.0, 41.0/255.0, 75.0/255.0, 1.0318 319 ];320 updateBuffer(vertexPositionBufferBot, updatedPosition, vertexBlueBufferBot, blue);321 322 updatedPosition = [323 (-0.9-delta)/3, -0.8/3, -0.1,324 (-0.9-delta)/3, -(1.4+delta)/3, -0.1,325 (-0.55-delta)/3, -0.8/3, -0.1,326 (0.9-delta)/3, -(1.4-delta)/3, -0.1,327 (0.9-delta)/3, -0.8/3, -0.1328 ];329 330 var orange = [331 232.0/255.0, 74.0/255.0, 39.0/255.0, 1.0,332 232.0/255.0, 74.0/255.0, 39.0/255.0, 1.0,333 232.0/255.0, 74.0/255.0, 39.0/255.0, 1.0,334 232.0/255.0, 74.0/255.0, 39.0/255.0, 1.0,335 232.0/255.0, 74.0/255.0, 39.0/255.0, 1.0,336 232.0/255.0, 74.0/255.0, 39.0/255.0, 1.0337 ];338 339 340 updateBuffer(vertexPositionBufferBotInner, updatedPosition, vertexOrangeBufferBot, orange);341 342 //draw everything 343 drawHelper(vertexPositionBufferTop, vertexBlueBufferTop, gl.TRIANGLE_STRIP)344 345 drawHelper(vertexPositionBufferMid, vertexBlueBufferMid, gl.TRIANGLE_STRIP)346 347 drawHelper(vertexPositionBufferBot, vertexBlueBufferBot, gl.TRIANGLE_STRIP) 348 349 drawHelper(vertexPositionBufferTopInner, vertexOrangeBufferTop, gl.TRIANGLE_STRIP)350 351 drawHelper(vertexPositionBufferMidInner, vertexOrangeBufferMid, gl.TRIANGLE_STRIP)352 drawHelper(vertexPositionBufferBotInner, vertexOrangeBufferBot, gl.TRIANGLE_STRIP)353}354/**355 * Animation to be called from tick. Updates globals and performs animation for each tick.356 */357function animateLogo() {358 //Shaking left and right359 if (clockwise)360 rotAngle = rotAngle+1.0;361 else rotAngle = rotAngle-1.0;362 363 if (Math.abs(rotAngle) > 30)364 clockwise = !clockwise365 366 //moving from left to top to right367 transX = transX + 0.01;368 if (transX > 1.5)369 transX = -1.5;370 371 transY = 0.8 - Math.abs(transX);372 373 //Upper part shakes in cycles374 if (clockwise)375 delta = delta + 0.015;376 else377 delta = delta - 0.015378}379//Setup and drawing for the Custom Buffers380/**381 * Populate the custom animation buffer with data382 */383function setUpBuffersCustom() {384 385 //Initialization386 vertexPositionBufferCustom = gl.createBuffer();387 vertexColorBufferCustom = gl.createBuffer();388 389 //vertex positions for the double square390 var vertices = [391 1.0, 1.0, 0.0,392 -1.0, 1.0, 0.0,393 -0.5, 0.5, 0.0,394 -1.0, -1.0, 0.0,395 -0.5, -0.5, 0.0,396 1.0, -1.0, 0.0,397 0.5, -0.5, 0.0,398 1.0, 1.0, 0.0,399 0.5, 0.5, 0.0,400 -0.5, 0.5, 0.0,401 0.5, 0.5, 0.0,402 -0.5, -0.5, 0.0,403 0.5, -0.5, 0.0,404 ];405 406 //vertex colors for the double square407 var colors = [408 1.0, 0.0, 0.0, 1.0,409 0.0, 1.0, 0.0, 1.0,410 1.0, 0.0, 0.0, 1.0,411 0.0, 0.0, 1.0, 1.0,412 0.0, 1.0, 0.0, 1.0,413 0.5, 0.5, 0.5, 1.0,414 0.0, 0.0, 1.0, 1.0,415 1.0, 0.0, 0.0, 1.0,416 0.5, 0.5, 0.5, 1.0,417 1.0, 0.0, 0.0, 1.0,418 0.5, 0.5, 0.5, 1.0,419 0.0, 1.0, 0.0, 1.0,420 0.0, 0.0, 1.0, 1.0 421 ];422 updateBuffer(vertexPositionBufferCustom, vertices, vertexColorBufferCustom, colors);423}424/**425 * draw call that changes the color of the custom animation426 */427function drawCustom() { 428 gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);429 gl.clear(gl.COLOR_BUFFER_BIT);430 431 //Don't do any transformation432 mat4.identity(mvMatrix);433 setMatrixUniforms()434 435 //Change color436 var newColor = [437 1.0-colorDelta, 0.0+colorDelta, 0.0, 1.0,438 0.0+colorDelta, 1.0-colorDelta, 0.0, 1.0,439 1.0-colorDelta, 0.0, 0.0+colorDelta, 1.0,440 0.0+colorDelta, 0.0+colorDelta, 1.0-colorDelta, 1.0,441 0.0, 1.0-colorDelta, 0.0+colorDelta, 1.0,442 0.5-colorDelta/2, 0.5+colorDelta/2, 0.5-colorDelta/2, 1.0,443 0.0+colorDelta, 0.0+colorDelta, 1.0-colorDelta, 1.0,444 1.0-colorDelta, 0.0+colorDelta, 0.0, 1.0,445 0.5+colorDelta/2, 0.5-colorDelta/2, 0.5+colorDelta/2, 1.0,446 1.0-colorDelta, 0.0, 0.0+colorDelta, 1.0,447 0.5+colorDelta/2, 0.5-colorDelta/2, 0.5+colorDelta/2, 1.0,448 0.0, 1.0-colorDelta, 0.0+colorDelta, 1.0,449 0.0+colorDelta, 0.0+colorDelta, 1.0-colorDelta, 1.0 450 ]451 452 updateBuffer(null, null, vertexColorBufferCustom, newColor);453 //draw custom buffer 454 drawHelper(vertexPositionBufferCustom, vertexColorBufferCustom, gl.TRIANGLE_STRIP);455}456/**457 * Animation to be called from tick. Updates globals and performs animation for each tick.458 */459function animateCustom() {460 if (flag)461 colorDelta = colorDelta + 0.005;462 else 463 colorDelta = colorDelta - 0.005;464 if (colorDelta >= 1 || colorDelta <= 0) {465 flag = !flag;466 }467}468//Common part for setup469/**470 * Startup function called from html code to start program.471 */472function startup() {473 474 canvas = document.getElementById("myGLCanvas");475 gl = createGLContext(canvas);476 setupShaders(); 477 478 479 document.getElementById("Logo").checked = true;480 setUpBuffersLogo();481 setUpBuffersCustom();482 483 gl.clearColor(0.0, 0.0, 0.0, 1.0);484 gl.enable(gl.DEPTH_TEST);485 486 tick();487}488/**489 * Tick called for every animation frame.490 */491function tick() {492 requestAnimFrame(tick);493 if (isLogo()) {494 drawLogo();495 animateLogo();496 }497 else {498 drawCustom();499 animateCustom();500 }501}502//Helper functions, used by both animations503/**504 * Translates degrees to radians505 * @param {Number} degrees Degree input to function506 * @return {Number} The radians that correspond to the degree input507 */508function degToRad(degrees) {509 return degrees * Math.PI / 180;510}511/**512 * Update buffers for a set of vertices, for both position and color. If one does not want to change the position/color, set the buffer variable to null, then the corresponding buffer won't be changed.513 * @param The buffer that will contain the position data514 * @param The vertex coodinates, given by an array of floats515 * @param The buffer that will contain the color data516 * @param The vertex colors, given by an array of floats; the length should match the number of vertices517 */518function updateBuffer(posBuffer, posData, colorBuffer, colorData) {519 520 //Vertex Position buffer521 if (posBuffer != null) {522 gl.bindBuffer(gl.ARRAY_BUFFER, posBuffer); 523 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(posData), gl.DYNAMIC_DRAW);524 posBuffer.itemSize = 3;525 posBuffer.numberOfItems = posData.length/3;526 }527 //Vertex color buffer528 if (colorBuffer != null) {529 gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);530 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colorData), gl.DYNAMIC_DRAW);531 colorBuffer.itemSize = 4;532 colorBuffer.numItems = colorData.length/4; 533 }534}535/**536 * Draw a set of vertices using a position buffer and a color buffer, using the provided interpretation of the positions537 * @param {positionBuffer} The buffer holding the position data538 * @param {colorBuffer} The buffer holding the color data539 * @param {glFlag} The way we interpret the position data, eg. gl.TRIANGLES540 */541function drawHelper(posBuffer, colorBuffer, glFlag) {542 gl.bindBuffer(gl.ARRAY_BUFFER, posBuffer);543 gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, 544 posBuffer.itemSize, gl.FLOAT, false, 0, 0);545 gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);546 547 gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);548 gl.vertexAttribPointer(shaderProgram.vertexColorAttribute, 549 colorBuffer.itemSize, gl.FLOAT, false, 0, 0);550 gl.enableVertexAttribArray(shaderProgram.vertexColorAttribute)551 552 gl.drawArrays(glFlag, 0, posBuffer.numberOfItems);...
triangles.js
Source:triangles.js
1/*2Triangles.js - v0.83Copyright (c) 2015 Taylor Lei4Licensed under the MIT license.5*/6var TriangleBG = function(opts) {7 if (opts.canvas.tagName !== "CANVAS") {8 console.log("Warning: triangles.js requires a canvas element!");9 return;10 }11 //set primary canvas and context12 this.canvas = opts.canvas;13 this.ctx = this.canvas.getContext("2d");14 //used when canvas is resized15 this.alternateElem = false;16 this.ctx.canvas.height = this.canvas.clientHeight;17 this.ctx.canvas.width = this.canvas.clientWidth;18 //rendering opts for padding, colors...; default values19 this.render = {20 offset : {x: -50, y:-50},21 pad : 2,22 mouseLightRadius : this.ctx.canvas.width/3,23 mouseLight : opts.mouseLight,24 mouseLightIncrement : 10,25 resizeAdjustment : false,26 variance : 1.3,27 pattern : "x*y",28 color1 : {29 hue: Math.round(180*Math.random()),30 saturation : Math.round(100*Math.random()),31 lightness: Math.round(100*Math.random())32 },33 color2 : {34 hue: 0,35 saturation : 0,36 lightness: 037 },38 colorDelta : {39 hue: 0.5,40 saturation : 0,41 lightness: 042 }43 }44 //default colors45 this.render.color2.hue = this.render.color1.hue;46 this.render.color2.saturation = this.render.color1.saturation;47 this.render.color2.lightness = this.render.color1.lightness + 2;48 this.net = {49 w:0, h:0,50 cellWidth: 100,51 cellHeight: 10052 };53 this.vert = new Array();54 this.mouse = {x:null,y:null}55 //set baseCell width and height from options:56 if (opts.alternateElem) {57 this.alternateElem = opts.alternateElem;58 }59 if (opts.cellWidth) {60 this.net.cellWidth = opts.cellWidth;61 }62 if (opts.cellHeight) {63 this.net.cellHeight = opts.cellHeight;64 }65 if (opts.mouseLight) {66 this.render.mouseLightRadius = opts.mouseLightRadius;67 if (opts.mouseLightRadius) {68 this.render.mouseLightRadius = opts.mouseLightRadius;69 }70 if (opts.mouseLightIncrement) {71 this.render.mouseLightIncrement = opts.mouseLightIncrement;72 }73 }74 if (opts.variance) {75 this.render.variance = opts.variance;76 }77 if (opts.pattern) {78 this.render.pattern = opts.pattern;79 }80 if (opts.resizeAdjustment) {81 this.render.resizeAdjustment = opts.resizeAdjustment;82 }83 if (opts.baseColor1) {84 if (opts.baseColor1.baseHue) {85 this.render.color1.hue = opts.baseColor1.baseHue;86 this.render.color2.hue = opts.baseColor1.baseHue;87 }88 if (opts.baseColor1.baseSaturation) {89 this.render.color1.saturation = opts.baseColor1.baseSaturation;90 this.render.color2.saturation = opts.baseColor1.baseSaturation;91 }92 if (opts.baseColor1.baseLightness) {93 this.render.color1.lightness = opts.baseColor1.baseLightness;94 this.render.color2.lightness = opts.baseColor1.baseLightness + 2;95 }96 }97 if (opts.baseColor2) {98 if (opts.baseColor2.baseHue) {99 this.render.color2.hue = opts.baseColor2.baseHue;100 }101 if (opts.baseColor2.baseSaturation) {102 this.render.color2.saturation = opts.baseColor2.baseSaturation;103 }104 if (opts.baseColor2.baseLightness) {105 this.render.color2.lightness = opts.baseColor2.baseLightness;106 }107 }108 if (opts.colorDelta) {109 if (opts.colorDelta.hue) {110 this.render.colorDelta.hue = opts.colorDelta.hue;111 }112 if (opts.colorDelta.saturation) {113 this.render.colorDelta.saturation = opts.colorDelta.saturation;114 }115 if (opts.colorDelta.lightness) {116 this.render.colorDelta.lightness = opts.colorDelta.lightness;117 }118 }119 //vertices120 this.generateNet();121 //window size change, so canvas doesn't deform122 window.addEventListener("resize", this, false);123 window.addEventListener("mousemove", this, false);124 this.handleEvent = function(e) {125 switch(e.type) {126 case "resize":127 if (this.alternateElem) {128 var dataURL = this.canvas.toDataURL("image/png");129 this.alternateElem.style.backgroundImage = "url("+dataURL+")";130 }131 if (this.render.resizeAdjustment) {132 this.ctx.canvas.height = this.canvas.clientHeight;133 this.ctx.canvas.width = this.canvas.clientWidth;134 }135 break;136 case "mousemove":137 var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;138 var scrollLeft = document.body.scrollLeft || document.documentElement.scrollLeft;139 this.mouse.x = e.clientX - this.render.offset.x - this.canvas.offsetLeft + scrollLeft;140 this.mouse.y = e.clientY - this.render.offset.y - this.canvas.offsetTop + scrollTop;141 break;142 }143 }144 this.delete = false;145};146TriangleBG.prototype.generateNet = function() {147 //fit a number of cellWidth to screen + so no problems can happen, pad by render.pad on each side148 this.net.w = Math.floor(screen.width/this.net.cellWidth) + this.render.pad*2; //+4 for edges149 this.net.h = Math.floor(screen.height/this.net.cellHeight) + this.render.pad*2;150 //render padding151 this.render.offset.x = -this.render.pad*this.net.cellWidth;152 this.render.offset.y = -this.render.pad*this.net.cellWidth;153 //generate vertices with random offsets154 var x;155 for (x = 0; x < this.net.w; x++) {156 this.vert.push([]);157 //how random are the offsets?158 var y;159 for (y = 0; y < this.net.h; y++) {160 this.vert[x].push({161 offset : {162 x: Math.floor(100 * Math.random()*this.net.cellWidth/this.render.variance - this.net.cellWidth/this.render.variance*2 ) / 100 , //x offset around -this.cellWidth/4 to this.cellWidth/4, to 2 decimals163 y: Math.floor(100 * Math.random()*this.net.cellHeight/this.render.variance - this.net.cellHeight/this.render.variance*2 ) / 100164 }165 });166 }167 }168 this.renderLoop();169 if (this.alternateElem) {170 var dataURL = this.canvas.toDataURL("image/png");171 }172 this.alternateElem.style.backgroundImage = "url("+dataURL+")";173};174TriangleBG.prototype.renderLoop = function() {175 if (this.delete === true) {176 return;177 }178 this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);179 this.ctx.translate(this.render.offset.x, this.render.offset.y);180 for (x = 0; x < this.net.w-1; x++) {181 var y;182 for (y = 0; y < this.net.h-1; y++) {183 var drawX, drawY;184 var centerX1=0, centerY1=0, centerX2=0, centerY2=0;185 var hueDelta = 0;186 var pattern;187 var saturationDelta = 0;188 var lightnessDelta = 0;189 var lightnessIncrement = 0;190 var mouseLightRadius = this.render.mouseLightRadius;191 //render pattern192 if (this.render.pattern === "x*y") {193 pattern = Math.abs(x*y);194 }195 else if (this.render.pattern === "x"){196 pattern = Math.abs(x);197 }198 else if (this.render.pattern === "y"){199 pattern = Math.abs(y);200 }201 hueDelta = pattern * this.render.colorDelta.hue;202 saturationDelta = 0;203 lightnessDelta = 0;204 //1st triangle205 this.ctx.beginPath();206 drawX = x * this.net.cellWidth + this.vert[x][y].offset.x;207 drawY = y * this.net.cellHeight + this.vert[x][y].offset.y;208 centerX1+=drawX;209 centerY1+=drawY;210 this.ctx.lineTo(drawX, drawY);211 drawX = x * this.net.cellWidth + this.vert[x][y+1].offset.x;212 drawY = (y+1) * this.net.cellHeight + this.vert[x][y+1].offset.y;213 centerX1+=drawX;214 centerY1+=drawY;215 this.ctx.lineTo(drawX, drawY);216 drawX = (x+1) * this.net.cellWidth + this.vert[x+1][y+1].offset.x;217 drawY = (y+1) * this.net.cellHeight + this.vert[x+1][y+1].offset.y;218 centerX1+=drawX;219 centerY1+=drawY;220 this.ctx.lineTo(drawX, drawY);221 this.ctx.closePath();222 centerX1 = centerX1/3;223 centerY1 = centerY1/3;224 if (this.render.mouseLight && Math.pow(Math.abs(this.mouse.x - centerX1),2) + Math.pow(Math.abs(this.mouse.y-centerY1),2) < Math.pow(mouseLightRadius,2)) {225 var radius = Math.sqrt( Math.pow(Math.abs(this.mouse.x-centerX1),2) + Math.pow(Math.abs(this.mouse.y - centerY1),2) );226 lightnessIncrement = (mouseLightRadius-radius)/(mouseLightRadius)*this.render.mouseLightIncrement;227 }228 var col1 = 'hsl(' + Math.floor(this.render.color1.hue + hueDelta) + ', ' + Math.floor(this.render.color1.saturation + saturationDelta) + '% ,' + (this.render.color1.lightness + lightnessDelta + lightnessIncrement) +'%)';229 this.ctx.fillStyle = col1;230 this.ctx.strokeStyle = col1;231 this.ctx.fill();232 this.ctx.stroke();233 //2nd triangle234 this.ctx.beginPath();235 drawX = x * this.net.cellWidth + this.vert[x][y].offset.x;236 drawY = y * this.net.cellHeight + this.vert[x][y].offset.y;237 centerX2+=drawX;238 centerY2+=drawY;239 this.ctx.lineTo(drawX, drawY);240 drawX = (x+1) * this.net.cellWidth + this.vert[x+1][y].offset.x;241 drawY = y * this.net.cellHeight + this.vert[x+1][y].offset.y;242 centerX2+=drawX;243 centerY2+=drawY;244 this.ctx.lineTo(drawX, drawY);245 drawX = (x+1) * this.net.cellWidth + this.vert[x+1][y+1].offset.x;246 drawY = (y+1) * this.net.cellHeight + this.vert[x+1][y+1].offset.y;247 centerX2+=drawX;248 centerY2+=drawY;249 this.ctx.lineTo(drawX, drawY);250 this.ctx.closePath();251 centerX2 = centerX2/3;252 centerY2 = centerY2/3;253 if (this.render.mouseLight && Math.pow(Math.abs(this.mouse.x - centerX2),2) + Math.pow(Math.abs(this.mouse.y-centerY2),2) < Math.pow(mouseLightRadius,2)) {254 var radius = Math.sqrt( Math.pow(Math.abs(this.mouse.x-centerX2),2) + Math.pow(Math.abs(this.mouse.y - centerY2),2) );255 lightnessIncrement = (mouseLightRadius-radius)/(mouseLightRadius)*this.render.mouseLightIncrement;256 }257 var col2 = 'hsl(' + Math.floor(this.render.color2.hue + hueDelta) + ', ' + Math.floor(this.render.color2.saturation + saturationDelta) + '% ,' + (this.render.color2.lightness + lightnessDelta + lightnessIncrement) +'%)';258 this.ctx.fillStyle = col2;259 this.ctx.strokeStyle = col2;260 this.ctx.fill();261 this.ctx.stroke();262 }263 }264 this.ctx.translate(-this.render.offset.x, -this.render.offset.y);265 if (this.render.mouseLight) {266 window.setTimeout(this.renderLoop.bind(this), 1000/30);267 }268};269TriangleBG.prototype.delete = function() {270 this.delete = true;...
index.js
Source:index.js
...60// function sum(...nums) {61// return nums.reduce((acc, val) => acc + val, 0);62// }63// https://en.wikipedia.org/wiki/Color_difference64function colorDelta(colorA, colorB, transformer) {65 return transformer(colorB) - transformer(colorA);66}67function distance(colorA, colorB) {68 return Math.sqrt(69 colorDelta(colorA, colorB, r) ** 2 +70 colorDelta(colorA, colorB, g) ** 2 +71 colorDelta(colorA, colorB, b) ** 272 );73}74function humanDistance(colorA, colorB) {75 const multiplier =76 Math.sqrt(colorDelta(colorA, colorB, r) ** 2) < 128 ? 2 : 3;77 return Math.sqrt(78 multiplier * colorDelta(colorA, colorB, r) ** 2 +79 4 * colorDelta(colorA, colorB, g) ** 2 +80 (multiplier === 2 ? 3 : 2) * colorDelta(colorA, colorB, b) ** 281 );82}83function redMean(colorA, colorB) {84 const rDist = (r(colorA) + r(colorB)) / 2;85 return Math.sqrt(86 (2 + rDist / 256) * colorDelta(colorA, colorB, r) ** 2 +87 4 * colorDelta(colorA, colorB, g) ** 2 +88 (2 + (255 - rDist) / 2) * colorDelta(colorA, colorB, b) ** 289 );90}91// <3 https://medium.com/@dtipson/creating-an-es6ish-compose-in-javascript-ac580b95104a92function compose(...fns) {93 return fns.reduce((f, g) => (...args) => f(g(...args)));94}95const white = Array(3).fill(225);96const CRITERIA = {97 light: "light",98 lightNA: "light-na",99 r: "r",100 g: "g",101 b: "b",102 a: "a",...
ColorUtil.js
Source:ColorUtil.js
...38 }39 static colorsEqual(colorA: Color, colorB: Color): boolean {40 return ColorUtil.colorComparator(colorA, colorB) === 0;41 }42 static colorDelta(colorA: Color, colorB: Color): ColorDelta {43 colorA = ColorUtil.normalizeToRGB(colorA);44 colorB = ColorUtil.normalizeToRGB(colorB);45 return {46 rDelta: colorA.r - colorB.r,47 gDelta: colorA.g - colorB.g,48 bDelta: colorA.b - colorB.b,49 aDelta: colorA.a - colorB.a50 };51 }52 static applyColorDelta(color: Color, delta: ColorDelta): Color {53 color = ColorUtil.normalizeToRGB(color);54 return {55 r: color.r + delta.rDelta,56 g: color.g + delta.gDelta,...
TableBody.js
Source:TableBody.js
1import React from "react";2import useMediaQuery from "@material-ui/core/useMediaQuery";3import numToRupee from "../../../Functions/NumToRupee";4const CellTitle = ({ data }) => {5 const matches = useMediaQuery("(min-width:600px)");6 return (7 <div8 style={{9 width: matches ? "15vw" : "30vw",10 padding: "1vw",11 margin: "0.5vw",12 color: "#6c757d",13 fontWeight: "600",14 backgroundColor: "#6c757d10",15 borderRadius: "4px",16 }}17 >18 {data}19 </div>20 );21};22const CellData = ({ data, dataDelta, color, colorDelta }) => {23 const matches = useMediaQuery("(min-width:600px)");24 return (25 <div26 style={{27 display: "flex",28 width: matches ? "10vw" : "20vw",29 justifyContent: "flex-end",30 flexWrap: "wrap",31 backgroundColor: "#6c757d10",32 margin: "0.5vw",33 borderRadius: "4px",34 }}35 >36 {dataDelta && dataDelta > 0 ? (37 <p38 style={{39 padding: "1vw 0.1vw",40 fontSize: "0.6rem",41 color: colorDelta,42 }}43 >44 ↑{numToRupee(dataDelta)}45 </p>46 ) : null}47 <p style={{ padding: "1vw", color: "#6c757d", fontWeight: "600" }}>48 {numToRupee(data)}49 </p>50 </div>51 );52};53function TableBody({ data }) {54 const matches = useMediaQuery("(min-width:600px)");55 return (56 <div>57 {data &&58 data.map((e) => (59 <div60 style={{61 display: "flex",62 }}63 key={e.dist}64 >65 <CellTitle data={e.dist} />66 <div67 style={{68 display: "flex",69 width: matches ? "45vw" : "69vw",70 justifyContent: "center",71 }}72 >73 <CellData74 data={e.confirmed}75 dataDelta={e.delta.confirmed}76 color="#dc3545"77 colorDelta="#dc354599"78 />79 <CellData80 data={e.active}81 dataDelta={e.delta.active}82 colorDelta="#dc354599"83 />84 <CellData85 data={e.recovered}86 dataDelta={e.delta.recovered}87 colorDelta="#28a74599"88 />89 <CellData90 data={e.deceased}91 dataDelta={e.delta.deceased}92 colorDelta="#6c757d99"93 />94 </div>95 </div>96 ))}97 </div>98 );99}...
sketch.js
Source:sketch.js
1// -2// Camminatore incontri-scontri 0.1 by Siria Gasperoni [Camminatori, incontri-scontri]3// 2021 © Siria Gasperoni, Daniele @Fupete, Irene @iretrtr and the course DS-2021 at DESIGN.unirsm,4// github.com/ds-2021-unirsm â github.com/fupete - github.com/siriagas5// Educational purposes, MIT License, 2021, San Marino6// Credits/Thanks to: 7//https://openprocessing.org/sketch/9029308//Ryno Hsiao9let walkers = [];10let walkersNum = 20;11function setup() {12 createCanvas(windowWidth, screen.availHeight);13 colorMode(HSB,10,10,10,255,);14 for (let i = 0; i < walkersNum; i++) {15 walkers.push(new walker());16 }17}18function draw() {19 blendMode(BLEND);20 background(0);21 blendMode(SCREEN);22 for (let i = 0; i < walkers.length; i++) {23walkers[i].move();24 walkers[i].dislpay();25 }26}27function walker() {28 this.x = 0;29 this.y = 0;30 this.c = random(9);31 this.w = random(5, 30);32 this.nx = random(1.00);33 this.ny = random(1.00);34 this.dx = random(0.005, 0.015);35 this.dy = random(0.005, 0.015);36 this.colorDelta = 0;37 this.colorSpeed = random(-1, 1) * 0.1;38//move39 this.move = function () {40 this.x = noise(this.nx, this.c * this.w) * width;41 this.y = noise(this.ny, this.c * this.w) * height;42 this.nx += this.dx;43 this.ny += this.dy;44 this.colorDelta += this.colorSpeed;45 }46//display47 this.dislpay = function () {48 for (let i = 1; i < 50; ++i) {49 strokeWeight(i * this.w * .1);50 stroke(abs((this.c+this.colorDelta))%9, 9, (50 - i) * .3, 9);51 //fill(9, 3);52 fill(abs((this.c+this.colorDelta))%9, 9, (50 - i) * .3, 6);53 circle(this.x, this.y, this.w);54 }...
colorDelta-test.js
Source:colorDelta-test.js
1const colorDelta = require('../colorDelta');2it('is large when comparing black and white', () => {3 expect(colorDelta([0, 0, 0, 255], [255, 255, 255, 255])).toBeGreaterThan(4 0.92,5 );6});7it('is small when comparing black and very dark grey', () => {8 expect(colorDelta([0, 0, 0, 255], [10, 10, 10, 255])).toBeLessThan(0.02);9});10it('is medium when comparing black and medium grey', () => {11 const delta = colorDelta([0, 0, 0, 255], [127, 127, 127, 255]);12 expect(delta).toBeGreaterThan(0.21);13 expect(delta).toBeLessThan(0.24);14});15it('is medium when comparing red and blue', () => {16 const delta = colorDelta([255, 0, 0, 255], [0, 0, 255, 255]);17 expect(delta).toBeGreaterThan(0.5);18 expect(delta).toBeLessThan(0.51);19});20it('is one when comparing transparent and white', () => {21 expect(colorDelta([0, 0, 0, 0], [255, 255, 255, 255])).toEqual(1);22});23it('is large when comparing transparent and black', () => {24 expect(colorDelta([0, 0, 0, 0], [0, 0, 0, 255])).toBeGreaterThan(0.92);25});26it('is large when comparing white and transparent', () => {27 expect(colorDelta([255, 255, 255, 255], [0, 0, 0, 0])).toBeGreaterThan(0.92);...
Using AI Code Generation
1const {chromium} = require('playwright');2(async () => {3 const browser = await chromium.launch({headless: false});4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({path: 'google.png'});7 await browser.close();8})();9const {chromium} = require('playwright');10(async () => {11 const browser = await chromium.launch({headless: false});12 const context = await browser.newContext();13 const page = await context.newPage();14 await page.screenshot({path: 'google.png'});15 await browser.close();16})();17const {chromium} = require('playwright');18(async () => {19 const browser = await chromium.launch({headless: false});20 const context = await browser.newContext();21 const page = await context.newPage();22 await page.screenshot({path: 'google.png'});23 await browser.close();24})();25const {chromium} = require('playwright');26(async () => {27 const browser = await chromium.launch({headless: false});28 const context = await browser.newContext();29 const page = await context.newPage();30 await page.screenshot({path: 'google.png'});31 await browser.close();32})();33const {chromium} = require('playwright');34(async () => {35 const browser = await chromium.launch({headless: false});36 const context = await browser.newContext();37 const page = await context.newPage();38 await page.screenshot({path: 'google.png'});39 await browser.close();40})();41const {chromium} = require('playwright');42(async () => {43 const browser = await chromium.launch({headless: false});44 const context = await browser.newContext();
Using AI Code Generation
1const {chromium} = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 const color = await page.evaluate(() => {6 const element = document.querySelector('h1');7 const color = window.getComputedStyle(element).color;8 return color;9 });10 const colorDelta = await page.colorDelta(color, 'black');11 console.log(colorDelta);12 await browser.close();13})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 const colorDelta = await page._delegate.colorDelta('#ff0000', '#0000ff');6 console.log(colorDelta);7 await browser.close();8})();9const { chromium } = require('playwright');10(async () => {11 const browser = await chromium.launch();12 const page = await browser.newPage();13 const colors = ['#ff0000', '#0000ff', '#00ff00'];14 const colorDelta = await page._delegate.colorDelta('#ff0000', colors);15 console.log(colorDelta);16 await browser.close();17})();18const { chromium } = require('playwright');19(async () => {20 const browser = await chromium.launch();21 const page = await browser.newPage();
Using AI Code Generation
1const {chromium} = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const color = await page.$eval('input[type="submit"]', el => window.getComputedStyle(el).backgroundColor);7 const colorDelta = await page.evaluate(color => window.colorDelta(color, 'rgb(255, 255, 255)'), color);8 console.log(colorDelta);9 await browser.close();10})();11const {chromium} = require('playwright');12(async () => {13 const browser = await chromium.launch();14 const context = await browser.newContext();15 const page = await context.newPage();16 const color = await page.$eval('input[type="submit"]', el => window.getComputedStyle(el).backgroundColor);17 const colorDelta = await page.evaluate(color => window.colorDeltaHSL(color, 'hsl(0, 0%, 100%)'), color);18 console.log(colorDelta);19 await browser.close();20})();
Using AI Code Generation
1const { colorDelta } = require('playwright-core/lib/server/supplements/recorder/recorderApp');2const color1 = '#000000';3const color2 = '#ffffff';4const delta = colorDelta(color1, color2);5console.log(delta);6const { colorDelta } = require('playwright-core/lib/server/supplements/recorder/recorderApp');7const color1 = '#000000';8const color2 = '#ffffff';9const delta = colorDelta(color1, color2);10console.log(delta);11const { colorDelta } = require('playwright-core/lib/server/supplements/recorder/recorderApp');12const color1 = '#000000';13const color2 = '#ffffff';14const delta = colorDelta(color1, color2);15console.log(delta);16const { colorDelta } = require('playwright-core/lib/server/supplements/recorder/recorderApp');17const color1 = '#000000';18const color2 = '#ffffff';19const delta = colorDelta(color1, color2);20console.log(delta);21const { colorDelta } = require('playwright-core/lib/server/supplements/recorder/recorderApp');22const color1 = '#000000';23const color2 = '#ffffff';24const delta = colorDelta(color1, color2);25console.log(delta);26const { colorDelta } = require('playwright-core/lib/server/supplements/recorder/recorderApp');27const color1 = '#000000';28const color2 = '#ffffff';29const delta = colorDelta(color1, color2);30console.log(delta);31const { colorDelta } = require('playwright-core/lib/server/supplements/recorder/recorderApp');32const color1 = '#000000';33const color2 = '#ffffff';34const delta = colorDelta(color1, color2);35console.log(delta);
Using AI Code Generation
1const { colorDelta } = require('playwright/lib/server/supplements/utils/colorDelta');2console.log(colorDelta('#ff0000', '#ff0000'));3console.log(colorDelta('#ff0000', '#00ff00'));4console.log(colorDelta('#ff0000', '#0000ff'));5const { chromium } = require('playwright');6const { colorDelta } = require('playwright/lib/server/supplements/utils/colorDelta');7(async () => {8 const browser = await chromium.launch();9 const context = await browser.newContext();10 const page = await context.newPage();11 const color = await page.$eval('.navbar__inner', (e) => window.getComputedStyle(e).backgroundColor);12 console.log(colorDelta(color, '#ffffff'));13 await browser.close();14})();
Using AI Code Generation
1const { colorDelta } = require('playwright/lib/server/supplements/recorder/recorderSupplement.js');2const result = colorDelta([0, 0, 0, 0], [0, 0, 0, 0]);3console.log(result);4const { colorDelta } = require('playwright/lib/client/recorderSupplement.js');5const result = colorDelta([0, 0, 0, 0], [0, 0, 0, 0]);6console.log(result);7const { colorDelta } = require('playwright/lib/client/recorderSupplement.js');8const result = colorDelta([0, 0, 0, 0], [0, 0, 0, 0]);9console.log(result);10const { colorDelta } = require('playwright/lib/client/recorderSupplement.js');11const result = colorDelta([0, 0, 0, 0], [0, 0, 0, 0]);12console.log(result);13const { colorDelta } = require('playwright/lib/client/recorderSupplement.js');14const result = colorDelta([0, 0, 0, 0], [0, 0, 0, 0]);15console.log(result);16const { colorDelta } = require('playwright/lib/client/recorderSupplement.js');17const result = colorDelta([0, 0, 0, 0], [0, 0, 0, 0]);18console.log(result);19const { colorDelta } = require('playwright/lib/client/recorderSupplement.js');20const result = colorDelta([0, 0, 0, 0], [0, 0, 0, 0]);21console.log(result);22const { colorDelta } = require('playwright/lib/client/recorderSup
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!